]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Added 'Reverse Directions' link
[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":181}],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 <feross@feross.org> <http://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 (value instanceof ArrayBuffer) {
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) || string instanceof ArrayBuffer) {
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 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2378 function isArrayBufferView (obj) {
2379   return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2380 }
2381
2382 function numberIsNaN (obj) {
2383   return obj !== obj // eslint-disable-line no-self-compare
2384 }
2385
2386 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2387 'use strict';
2388
2389 module.exports = earcut;
2390
2391 function earcut(data, holeIndices, dim) {
2392
2393     dim = dim || 2;
2394
2395     var hasHoles = holeIndices && holeIndices.length,
2396         outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2397         outerNode = linkedList(data, 0, outerLen, dim, true),
2398         triangles = [];
2399
2400     if (!outerNode) return triangles;
2401
2402     var minX, minY, maxX, maxY, x, y, size;
2403
2404     if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2405
2406     // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2407     if (data.length > 80 * dim) {
2408         minX = maxX = data[0];
2409         minY = maxY = data[1];
2410
2411         for (var i = dim; i < outerLen; i += dim) {
2412             x = data[i];
2413             y = data[i + 1];
2414             if (x < minX) minX = x;
2415             if (y < minY) minY = y;
2416             if (x > maxX) maxX = x;
2417             if (y > maxY) maxY = y;
2418         }
2419
2420         // minX, minY and size are later used to transform coords into integers for z-order calculation
2421         size = Math.max(maxX - minX, maxY - minY);
2422     }
2423
2424     earcutLinked(outerNode, triangles, dim, minX, minY, size);
2425
2426     return triangles;
2427 }
2428
2429 // create a circular doubly linked list from polygon points in the specified winding order
2430 function linkedList(data, start, end, dim, clockwise) {
2431     var i, last;
2432
2433     if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2434         for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2435     } else {
2436         for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2437     }
2438
2439     if (last && equals(last, last.next)) {
2440         removeNode(last);
2441         last = last.next;
2442     }
2443
2444     return last;
2445 }
2446
2447 // eliminate colinear or duplicate points
2448 function filterPoints(start, end) {
2449     if (!start) return start;
2450     if (!end) end = start;
2451
2452     var p = start,
2453         again;
2454     do {
2455         again = false;
2456
2457         if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2458             removeNode(p);
2459             p = end = p.prev;
2460             if (p === p.next) return null;
2461             again = true;
2462
2463         } else {
2464             p = p.next;
2465         }
2466     } while (again || p !== end);
2467
2468     return end;
2469 }
2470
2471 // main ear slicing loop which triangulates a polygon (given as a linked list)
2472 function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
2473     if (!ear) return;
2474
2475     // interlink polygon nodes in z-order
2476     if (!pass && size) indexCurve(ear, minX, minY, size);
2477
2478     var stop = ear,
2479         prev, next;
2480
2481     // iterate through ears, slicing them one by one
2482     while (ear.prev !== ear.next) {
2483         prev = ear.prev;
2484         next = ear.next;
2485
2486         if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
2487             // cut off the triangle
2488             triangles.push(prev.i / dim);
2489             triangles.push(ear.i / dim);
2490             triangles.push(next.i / dim);
2491
2492             removeNode(ear);
2493
2494             // skipping the next vertice leads to less sliver triangles
2495             ear = next.next;
2496             stop = next.next;
2497
2498             continue;
2499         }
2500
2501         ear = next;
2502
2503         // if we looped through the whole remaining polygon and can't find any more ears
2504         if (ear === stop) {
2505             // try filtering points and slicing again
2506             if (!pass) {
2507                 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
2508
2509             // if this didn't work, try curing all small self-intersections locally
2510             } else if (pass === 1) {
2511                 ear = cureLocalIntersections(ear, triangles, dim);
2512                 earcutLinked(ear, triangles, dim, minX, minY, size, 2);
2513
2514             // as a last resort, try splitting the remaining polygon into two
2515             } else if (pass === 2) {
2516                 splitEarcut(ear, triangles, dim, minX, minY, size);
2517             }
2518
2519             break;
2520         }
2521     }
2522 }
2523
2524 // check whether a polygon node forms a valid ear with adjacent nodes
2525 function isEar(ear) {
2526     var a = ear.prev,
2527         b = ear,
2528         c = ear.next;
2529
2530     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2531
2532     // now make sure we don't have other points inside the potential ear
2533     var p = ear.next.next;
2534
2535     while (p !== ear.prev) {
2536         if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2537             area(p.prev, p, p.next) >= 0) return false;
2538         p = p.next;
2539     }
2540
2541     return true;
2542 }
2543
2544 function isEarHashed(ear, minX, minY, size) {
2545     var a = ear.prev,
2546         b = ear,
2547         c = ear.next;
2548
2549     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2550
2551     // triangle bbox; min & max are calculated like this for speed
2552     var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2553         minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2554         maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2555         maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2556
2557     // z-order range for the current triangle bbox;
2558     var minZ = zOrder(minTX, minTY, minX, minY, size),
2559         maxZ = zOrder(maxTX, maxTY, minX, minY, size);
2560
2561     // first look for points inside the triangle in increasing z-order
2562     var p = ear.nextZ;
2563
2564     while (p && p.z <= maxZ) {
2565         if (p !== ear.prev && p !== ear.next &&
2566             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2567             area(p.prev, p, p.next) >= 0) return false;
2568         p = p.nextZ;
2569     }
2570
2571     // then look for points in decreasing z-order
2572     p = ear.prevZ;
2573
2574     while (p && p.z >= minZ) {
2575         if (p !== ear.prev && p !== ear.next &&
2576             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2577             area(p.prev, p, p.next) >= 0) return false;
2578         p = p.prevZ;
2579     }
2580
2581     return true;
2582 }
2583
2584 // go through all polygon nodes and cure small local self-intersections
2585 function cureLocalIntersections(start, triangles, dim) {
2586     var p = start;
2587     do {
2588         var a = p.prev,
2589             b = p.next.next;
2590
2591         if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2592
2593             triangles.push(a.i / dim);
2594             triangles.push(p.i / dim);
2595             triangles.push(b.i / dim);
2596
2597             // remove two nodes involved
2598             removeNode(p);
2599             removeNode(p.next);
2600
2601             p = start = b;
2602         }
2603         p = p.next;
2604     } while (p !== start);
2605
2606     return p;
2607 }
2608
2609 // try splitting polygon into two and triangulate them independently
2610 function splitEarcut(start, triangles, dim, minX, minY, size) {
2611     // look for a valid diagonal that divides the polygon into two
2612     var a = start;
2613     do {
2614         var b = a.next.next;
2615         while (b !== a.prev) {
2616             if (a.i !== b.i && isValidDiagonal(a, b)) {
2617                 // split the polygon in two by the diagonal
2618                 var c = splitPolygon(a, b);
2619
2620                 // filter colinear points around the cuts
2621                 a = filterPoints(a, a.next);
2622                 c = filterPoints(c, c.next);
2623
2624                 // run earcut on each half
2625                 earcutLinked(a, triangles, dim, minX, minY, size);
2626                 earcutLinked(c, triangles, dim, minX, minY, size);
2627                 return;
2628             }
2629             b = b.next;
2630         }
2631         a = a.next;
2632     } while (a !== start);
2633 }
2634
2635 // link every hole into the outer loop, producing a single-ring polygon without holes
2636 function eliminateHoles(data, holeIndices, outerNode, dim) {
2637     var queue = [],
2638         i, len, start, end, list;
2639
2640     for (i = 0, len = holeIndices.length; i < len; i++) {
2641         start = holeIndices[i] * dim;
2642         end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2643         list = linkedList(data, start, end, dim, false);
2644         if (list === list.next) list.steiner = true;
2645         queue.push(getLeftmost(list));
2646     }
2647
2648     queue.sort(compareX);
2649
2650     // process holes from left to right
2651     for (i = 0; i < queue.length; i++) {
2652         eliminateHole(queue[i], outerNode);
2653         outerNode = filterPoints(outerNode, outerNode.next);
2654     }
2655
2656     return outerNode;
2657 }
2658
2659 function compareX(a, b) {
2660     return a.x - b.x;
2661 }
2662
2663 // find a bridge between vertices that connects hole with an outer ring and and link it
2664 function eliminateHole(hole, outerNode) {
2665     outerNode = findHoleBridge(hole, outerNode);
2666     if (outerNode) {
2667         var b = splitPolygon(outerNode, hole);
2668         filterPoints(b, b.next);
2669     }
2670 }
2671
2672 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2673 function findHoleBridge(hole, outerNode) {
2674     var p = outerNode,
2675         hx = hole.x,
2676         hy = hole.y,
2677         qx = -Infinity,
2678         m;
2679
2680     // find a segment intersected by a ray from the hole's leftmost point to the left;
2681     // segment's endpoint with lesser x will be potential connection point
2682     do {
2683         if (hy <= p.y && hy >= p.next.y) {
2684             var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2685             if (x <= hx && x > qx) {
2686                 qx = x;
2687                 if (x === hx) {
2688                     if (hy === p.y) return p;
2689                     if (hy === p.next.y) return p.next;
2690                 }
2691                 m = p.x < p.next.x ? p : p.next;
2692             }
2693         }
2694         p = p.next;
2695     } while (p !== outerNode);
2696
2697     if (!m) return null;
2698
2699     if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2700
2701     // look for points inside the triangle of hole point, segment intersection and endpoint;
2702     // if there are no points found, we have a valid connection;
2703     // otherwise choose the point of the minimum angle with the ray as connection point
2704
2705     var stop = m,
2706         mx = m.x,
2707         my = m.y,
2708         tanMin = Infinity,
2709         tan;
2710
2711     p = m.next;
2712
2713     while (p !== stop) {
2714         if (hx >= p.x && p.x >= mx &&
2715                 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2716
2717             tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2718
2719             if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2720                 m = p;
2721                 tanMin = tan;
2722             }
2723         }
2724
2725         p = p.next;
2726     }
2727
2728     return m;
2729 }
2730
2731 // interlink polygon nodes in z-order
2732 function indexCurve(start, minX, minY, size) {
2733     var p = start;
2734     do {
2735         if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
2736         p.prevZ = p.prev;
2737         p.nextZ = p.next;
2738         p = p.next;
2739     } while (p !== start);
2740
2741     p.prevZ.nextZ = null;
2742     p.prevZ = null;
2743
2744     sortLinked(p);
2745 }
2746
2747 // Simon Tatham's linked list merge sort algorithm
2748 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2749 function sortLinked(list) {
2750     var i, p, q, e, tail, numMerges, pSize, qSize,
2751         inSize = 1;
2752
2753     do {
2754         p = list;
2755         list = null;
2756         tail = null;
2757         numMerges = 0;
2758
2759         while (p) {
2760             numMerges++;
2761             q = p;
2762             pSize = 0;
2763             for (i = 0; i < inSize; i++) {
2764                 pSize++;
2765                 q = q.nextZ;
2766                 if (!q) break;
2767             }
2768
2769             qSize = inSize;
2770
2771             while (pSize > 0 || (qSize > 0 && q)) {
2772
2773                 if (pSize === 0) {
2774                     e = q;
2775                     q = q.nextZ;
2776                     qSize--;
2777                 } else if (qSize === 0 || !q) {
2778                     e = p;
2779                     p = p.nextZ;
2780                     pSize--;
2781                 } else if (p.z <= q.z) {
2782                     e = p;
2783                     p = p.nextZ;
2784                     pSize--;
2785                 } else {
2786                     e = q;
2787                     q = q.nextZ;
2788                     qSize--;
2789                 }
2790
2791                 if (tail) tail.nextZ = e;
2792                 else list = e;
2793
2794                 e.prevZ = tail;
2795                 tail = e;
2796             }
2797
2798             p = q;
2799         }
2800
2801         tail.nextZ = null;
2802         inSize *= 2;
2803
2804     } while (numMerges > 1);
2805
2806     return list;
2807 }
2808
2809 // z-order of a point given coords and size of the data bounding box
2810 function zOrder(x, y, minX, minY, size) {
2811     // coords are transformed into non-negative 15-bit integer range
2812     x = 32767 * (x - minX) / size;
2813     y = 32767 * (y - minY) / size;
2814
2815     x = (x | (x << 8)) & 0x00FF00FF;
2816     x = (x | (x << 4)) & 0x0F0F0F0F;
2817     x = (x | (x << 2)) & 0x33333333;
2818     x = (x | (x << 1)) & 0x55555555;
2819
2820     y = (y | (y << 8)) & 0x00FF00FF;
2821     y = (y | (y << 4)) & 0x0F0F0F0F;
2822     y = (y | (y << 2)) & 0x33333333;
2823     y = (y | (y << 1)) & 0x55555555;
2824
2825     return x | (y << 1);
2826 }
2827
2828 // find the leftmost node of a polygon ring
2829 function getLeftmost(start) {
2830     var p = start,
2831         leftmost = start;
2832     do {
2833         if (p.x < leftmost.x) leftmost = p;
2834         p = p.next;
2835     } while (p !== start);
2836
2837     return leftmost;
2838 }
2839
2840 // check if a point lies within a convex triangle
2841 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2842     return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2843            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2844            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2845 }
2846
2847 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2848 function isValidDiagonal(a, b) {
2849     return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2850            locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2851 }
2852
2853 // signed area of a triangle
2854 function area(p, q, r) {
2855     return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2856 }
2857
2858 // check if two points are equal
2859 function equals(p1, p2) {
2860     return p1.x === p2.x && p1.y === p2.y;
2861 }
2862
2863 // check if two segments intersect
2864 function intersects(p1, q1, p2, q2) {
2865     if ((equals(p1, q1) && equals(p2, q2)) ||
2866         (equals(p1, q2) && equals(p2, q1))) return true;
2867     return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2868            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2869 }
2870
2871 // check if a polygon diagonal intersects any polygon segments
2872 function intersectsPolygon(a, b) {
2873     var p = a;
2874     do {
2875         if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2876                 intersects(p, p.next, a, b)) return true;
2877         p = p.next;
2878     } while (p !== a);
2879
2880     return false;
2881 }
2882
2883 // check if a polygon diagonal is locally inside the polygon
2884 function locallyInside(a, b) {
2885     return area(a.prev, a, a.next) < 0 ?
2886         area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2887         area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2888 }
2889
2890 // check if the middle point of a polygon diagonal is inside the polygon
2891 function middleInside(a, b) {
2892     var p = a,
2893         inside = false,
2894         px = (a.x + b.x) / 2,
2895         py = (a.y + b.y) / 2;
2896     do {
2897         if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2898             inside = !inside;
2899         p = p.next;
2900     } while (p !== a);
2901
2902     return inside;
2903 }
2904
2905 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2906 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2907 function splitPolygon(a, b) {
2908     var a2 = new Node(a.i, a.x, a.y),
2909         b2 = new Node(b.i, b.x, b.y),
2910         an = a.next,
2911         bp = b.prev;
2912
2913     a.next = b;
2914     b.prev = a;
2915
2916     a2.next = an;
2917     an.prev = a2;
2918
2919     b2.next = a2;
2920     a2.prev = b2;
2921
2922     bp.next = b2;
2923     b2.prev = bp;
2924
2925     return b2;
2926 }
2927
2928 // create a node and optionally link it with previous one (in a circular doubly linked list)
2929 function insertNode(i, x, y, last) {
2930     var p = new Node(i, x, y);
2931
2932     if (!last) {
2933         p.prev = p;
2934         p.next = p;
2935
2936     } else {
2937         p.next = last.next;
2938         p.prev = last;
2939         last.next.prev = p;
2940         last.next = p;
2941     }
2942     return p;
2943 }
2944
2945 function removeNode(p) {
2946     p.next.prev = p.prev;
2947     p.prev.next = p.next;
2948
2949     if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2950     if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2951 }
2952
2953 function Node(i, x, y) {
2954     // vertice index in coordinates array
2955     this.i = i;
2956
2957     // vertex coordinates
2958     this.x = x;
2959     this.y = y;
2960
2961     // previous and next vertice nodes in a polygon ring
2962     this.prev = null;
2963     this.next = null;
2964
2965     // z-order curve value
2966     this.z = null;
2967
2968     // previous and next nodes in z-order
2969     this.prevZ = null;
2970     this.nextZ = null;
2971
2972     // indicates whether this is a steiner point
2973     this.steiner = false;
2974 }
2975
2976 // return a percentage difference between the polygon area and its triangulation area;
2977 // used to verify correctness of triangulation
2978 earcut.deviation = function (data, holeIndices, dim, triangles) {
2979     var hasHoles = holeIndices && holeIndices.length;
2980     var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2981
2982     var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2983     if (hasHoles) {
2984         for (var i = 0, len = holeIndices.length; i < len; i++) {
2985             var start = holeIndices[i] * dim;
2986             var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2987             polygonArea -= Math.abs(signedArea(data, start, end, dim));
2988         }
2989     }
2990
2991     var trianglesArea = 0;
2992     for (i = 0; i < triangles.length; i += 3) {
2993         var a = triangles[i] * dim;
2994         var b = triangles[i + 1] * dim;
2995         var c = triangles[i + 2] * dim;
2996         trianglesArea += Math.abs(
2997             (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
2998             (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
2999     }
3000
3001     return polygonArea === 0 && trianglesArea === 0 ? 0 :
3002         Math.abs((trianglesArea - polygonArea) / polygonArea);
3003 };
3004
3005 function signedArea(data, start, end, dim) {
3006     var sum = 0;
3007     for (var i = start, j = end - dim; i < end; i += dim) {
3008         sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3009         j = i;
3010     }
3011     return sum;
3012 }
3013
3014 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3015 earcut.flatten = function (data) {
3016     var dim = data[0][0].length,
3017         result = {vertices: [], holes: [], dimensions: dim},
3018         holeIndex = 0;
3019
3020     for (var i = 0; i < data.length; i++) {
3021         for (var j = 0; j < data[i].length; j++) {
3022             for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3023         }
3024         if (i > 0) {
3025             holeIndex += data[i - 1].length;
3026             result.holes.push(holeIndex);
3027         }
3028     }
3029     return result;
3030 };
3031
3032 },{}],9:[function(require,module,exports){
3033 'use strict';
3034
3035 var OneVersionConstraint = require('individual/one-version');
3036
3037 var MY_VERSION = '7';
3038 OneVersionConstraint('ev-store', MY_VERSION);
3039
3040 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3041
3042 module.exports = EvStore;
3043
3044 function EvStore(elem) {
3045     var hash = elem[hashKey];
3046
3047     if (!hash) {
3048         hash = elem[hashKey] = {};
3049     }
3050
3051     return hash;
3052 }
3053
3054 },{"individual/one-version":19}],10:[function(require,module,exports){
3055 'use strict';
3056 var request = require('./request');
3057 var buildQueryObject = require('./buildQueryObject');
3058 var isArray = Array.isArray;
3059
3060 function simpleExtend(obj, obj2) {
3061   var prop;
3062   for (prop in obj2) {
3063     obj[prop] = obj2[prop];
3064   }
3065   return obj;
3066 }
3067
3068 function XMLHttpSource(jsongUrl, config) {
3069   this._jsongUrl = jsongUrl;
3070   if (typeof config === 'number') {
3071     var newConfig = {
3072       timeout: config
3073     };
3074     config = newConfig;
3075   }
3076   this._config = simpleExtend({
3077     timeout: 15000,
3078     headers: {}
3079   }, config || {});
3080 }
3081
3082 XMLHttpSource.prototype = {
3083   // because javascript
3084   constructor: XMLHttpSource,
3085   /**
3086    * buildQueryObject helper
3087    */
3088   buildQueryObject: buildQueryObject,
3089
3090   /**
3091    * @inheritDoc DataSource#get
3092    */
3093   get: function httpSourceGet(pathSet) {
3094     var method = 'GET';
3095     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3096       paths: pathSet,
3097       method: 'get'
3098     });
3099     var config = simpleExtend(queryObject, this._config);
3100     // pass context for onBeforeRequest callback
3101     var context = this;
3102     return request(method, config, context);
3103   },
3104
3105   /**
3106    * @inheritDoc DataSource#set
3107    */
3108   set: function httpSourceSet(jsongEnv) {
3109     var method = 'POST';
3110     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3111       jsonGraph: jsongEnv,
3112       method: 'set'
3113     });
3114     var config = simpleExtend(queryObject, this._config);
3115     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3116     
3117     // pass context for onBeforeRequest callback
3118     var context = this;
3119     return request(method, config, context);
3120
3121   },
3122
3123   /**
3124    * @inheritDoc DataSource#call
3125    */
3126   call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3127     // arguments defaults
3128     args = args || [];
3129     pathSuffix = pathSuffix || [];
3130     paths = paths || [];
3131
3132     var method = 'POST';
3133     var queryData = [];
3134     queryData.push('method=call');
3135     queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3136     queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3137     queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3138     queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3139
3140     var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3141     var config = simpleExtend(queryObject, this._config);
3142     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3143     
3144     // pass context for onBeforeRequest callback
3145     var context = this;
3146     return request(method, config, context);
3147   }
3148 };
3149 // ES6 modules
3150 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3151 XMLHttpSource['default'] = XMLHttpSource;
3152 // commonjs
3153 module.exports = XMLHttpSource;
3154
3155 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3156 'use strict';
3157 module.exports = function buildQueryObject(url, method, queryData) {
3158   var qData = [];
3159   var keys;
3160   var data = {url: url};
3161   var isQueryParamUrl = url.indexOf('?') !== -1;
3162   var startUrl = (isQueryParamUrl) ? '&' : '?';
3163
3164   if (typeof queryData === 'string') {
3165     qData.push(queryData);
3166   } else {
3167
3168     keys = Object.keys(queryData);
3169     keys.forEach(function (k) {
3170       var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3171       qData.push(k + '=' + encodeURIComponent(value));
3172     });
3173   }
3174
3175   if (method === 'GET') {
3176     data.url += startUrl + qData.join('&');
3177   } else {
3178     data.data = qData.join('&');
3179   }
3180
3181   return data;
3182 };
3183
3184 },{}],12:[function(require,module,exports){
3185 (function (global){
3186 'use strict';
3187 // Get CORS support even for older IE
3188 module.exports = function getCORSRequest() {
3189     var xhr = new global.XMLHttpRequest();
3190     if ('withCredentials' in xhr) {
3191         return xhr;
3192     } else if (!!global.XDomainRequest) {
3193         return new XDomainRequest();
3194     } else {
3195         throw new Error('CORS is not supported by your browser');
3196     }
3197 };
3198
3199 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3200
3201 },{}],13:[function(require,module,exports){
3202 (function (global){
3203 'use strict';
3204 module.exports = function getXMLHttpRequest() {
3205   var progId,
3206     progIds,
3207     i;
3208   if (global.XMLHttpRequest) {
3209     return new global.XMLHttpRequest();
3210   } else {
3211     try {
3212     progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3213     for (i = 0; i < 3; i++) {
3214       try {
3215         progId = progIds[i];
3216         if (new global.ActiveXObject(progId)) {
3217           break;
3218         }
3219       } catch(e) { }
3220     }
3221     return new global.ActiveXObject(progId);
3222     } catch (e) {
3223     throw new Error('XMLHttpRequest is not supported by your browser');
3224     }
3225   }
3226 };
3227
3228 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3229
3230 },{}],14:[function(require,module,exports){
3231 'use strict';
3232 var getXMLHttpRequest = require('./getXMLHttpRequest');
3233 var getCORSRequest = require('./getCORSRequest');
3234 var hasOwnProp = Object.prototype.hasOwnProperty;
3235
3236 var noop = function() {};
3237
3238 function Observable() {}
3239
3240 Observable.create = function(subscribe) {
3241   var o = new Observable();
3242
3243   o.subscribe = function(onNext, onError, onCompleted) {
3244
3245     var observer;
3246     var disposable;
3247
3248     if (typeof onNext === 'function') {
3249         observer = {
3250             onNext: onNext,
3251             onError: (onError || noop),
3252             onCompleted: (onCompleted || noop)
3253         };
3254     } else {
3255         observer = onNext;
3256     }
3257
3258     disposable = subscribe(observer);
3259
3260     if (typeof disposable === 'function') {
3261       return {
3262         dispose: disposable
3263       };
3264     } else {
3265       return disposable;
3266     }
3267   };
3268
3269   return o;
3270 };
3271
3272 function request(method, options, context) {
3273   return Observable.create(function requestObserver(observer) {
3274
3275     var config = {
3276       method: method || 'GET',
3277       crossDomain: false,
3278       async: true,
3279       headers: {},
3280       responseType: 'json'
3281     };
3282
3283     var xhr,
3284       isDone,
3285       headers,
3286       header,
3287       prop;
3288
3289     for (prop in options) {
3290       if (hasOwnProp.call(options, prop)) {
3291         config[prop] = options[prop];
3292       }
3293     }
3294
3295     // Add request with Headers
3296     if (!config.crossDomain && !config.headers['X-Requested-With']) {
3297       config.headers['X-Requested-With'] = 'XMLHttpRequest';
3298     }
3299
3300     // allow the user to mutate the config open
3301     if (context.onBeforeRequest != null) {
3302       context.onBeforeRequest(config);
3303     }
3304
3305     // create xhr
3306     try {
3307       xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3308     } catch (err) {
3309       observer.onError(err);
3310     }
3311     try {
3312       // Takes the url and opens the connection
3313       if (config.user) {
3314         xhr.open(config.method, config.url, config.async, config.user, config.password);
3315       } else {
3316         xhr.open(config.method, config.url, config.async);
3317       }
3318
3319       // Sets timeout information
3320       xhr.timeout = config.timeout;
3321
3322       // Anything but explicit false results in true.
3323       xhr.withCredentials = config.withCredentials !== false;
3324
3325       // Fills the request headers
3326       headers = config.headers;
3327       for (header in headers) {
3328         if (hasOwnProp.call(headers, header)) {
3329           xhr.setRequestHeader(header, headers[header]);
3330         }
3331       }
3332
3333       if (config.responseType) {
3334         try {
3335           xhr.responseType = config.responseType;
3336         } catch (e) {
3337           // WebKit added support for the json responseType value on 09/03/2013
3338           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3339           // known to throw when setting the value "json" as the response type. Other older
3340           // browsers implementing the responseType
3341           //
3342           // The json response type can be ignored if not supported, because JSON payloads are
3343           // parsed on the client-side regardless.
3344           if (config.responseType !== 'json') {
3345             throw e;
3346           }
3347         }
3348       }
3349
3350       xhr.onreadystatechange = function onreadystatechange(e) {
3351         // Complete
3352         if (xhr.readyState === 4) {
3353           if (!isDone) {
3354             isDone = true;
3355             onXhrLoad(observer, xhr, e);
3356           }
3357         }
3358       };
3359
3360       // Timeout
3361       xhr.ontimeout = function ontimeout(e) {
3362         if (!isDone) {
3363           isDone = true;
3364           onXhrError(observer, xhr, 'timeout error', e);
3365         }
3366       };
3367
3368       // Send Request
3369       xhr.send(config.data);
3370
3371     } catch (e) {
3372       observer.onError(e);
3373     }
3374     // Dispose
3375     return function dispose() {
3376       // Doesn't work in IE9
3377       if (!isDone && xhr.readyState !== 4) {
3378         isDone = true;
3379         xhr.abort();
3380       }
3381     };//Dispose
3382   });
3383 }
3384
3385 /*
3386  * General handling of ultimate failure (after appropriate retries)
3387  */
3388 function _handleXhrError(observer, textStatus, errorThrown) {
3389   // IE9: cross-domain request may be considered errors
3390   if (!errorThrown) {
3391     errorThrown = new Error(textStatus);
3392   }
3393
3394   observer.onError(errorThrown);
3395 }
3396
3397 function onXhrLoad(observer, xhr, e) {
3398   var responseData,
3399     responseObject,
3400     responseType;
3401
3402   // If there's no observer, the request has been (or is being) cancelled.
3403   if (xhr && observer) {
3404     responseType = xhr.responseType;
3405     // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3406     // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3407     responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3408
3409     // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3410     var status = (xhr.status === 1223) ? 204 : xhr.status;
3411
3412     if (status >= 200 && status <= 399) {
3413       try {
3414         if (responseType !== 'json') {
3415           responseData = JSON.parse(responseData || '');
3416         }
3417         if (typeof responseData === 'string') {
3418           responseData = JSON.parse(responseData || '');
3419         }
3420       } catch (e) {
3421         _handleXhrError(observer, 'invalid json', e);
3422       }
3423       observer.onNext(responseData);
3424       observer.onCompleted();
3425       return;
3426
3427     } else if (status === 401 || status === 403 || status === 407) {
3428
3429       return _handleXhrError(observer, responseData);
3430
3431     } else if (status === 410) {
3432       // TODO: Retry ?
3433       return _handleXhrError(observer, responseData);
3434
3435     } else if (status === 408 || status === 504) {
3436       // TODO: Retry ?
3437       return _handleXhrError(observer, responseData);
3438
3439     } else {
3440
3441       return _handleXhrError(observer, responseData || ('Response code ' + status));
3442
3443     }//if
3444   }//if
3445 }//onXhrLoad
3446
3447 function onXhrError(observer, xhr, status, e) {
3448   _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3449 }
3450
3451 module.exports = request;
3452
3453 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3454 (function (global){
3455 !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.falcor=t()}}(function(){var t;return function e(t,n,r){function o(s,u){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var p=n[s]={exports:{}};t[s][0].call(p.exports,function(e){var n=t[s][1][e];return o(n?n:e)},p,p.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(t,e,n){var r=t(32),o=t(130);r.atom=o.atom,r.ref=o.ref,r.error=o.error,r.pathValue=o.pathValue,r.HttpDataSource=t(125),e.exports=r},{125:125,130:130,32:32}],2:[function(t,e,n){function r(t){var e=t||{};this._root=e._root||new o(e),this._path=e.path||e._path||[],this._scheduler=e.scheduler||e._scheduler||new l,this._source=e.source||e._source,this._request=e.request||e._request||new s(this,this._scheduler),this._ID=N++,"number"==typeof e.maxSize?this._maxSize=e.maxSize:this._maxSize=e._maxSize||r.prototype._maxSize,"number"==typeof e.collectRatio?this._collectRatio=e.collectRatio:this._collectRatio=e._collectRatio||r.prototype._collectRatio,(e.boxed||e.hasOwnProperty("_boxed"))&&(this._boxed=e.boxed||e._boxed),(e.materialized||e.hasOwnProperty("_materialized"))&&(this._materialized=e.materialized||e._materialized),"boolean"==typeof e.treatErrorsAsValues?this._treatErrorsAsValues=e.treatErrorsAsValues:e.hasOwnProperty("_treatErrorsAsValues")&&(this._treatErrorsAsValues=e._treatErrorsAsValues),e.cache&&this.setCache(e.cache)}var o=t(4),i=t(3),s=t(55),u=t(64),a=t(65),c=t(61),p=t(63),h=t(73),f=t(75),l=t(74),d=t(81),v=t(84),y=t(49),b=t(134),m=t(88),g=t(100),w=t(96),x=t(102),_=t(98),S=t(99),E=t(77),C=t(76),A=t(130),N=0,k=t(116),O=function(){},P=t(14),j=t(19),D={pathValue:!0,pathSyntax:!0,json:!0,jsonGraph:!0},q=t(72);e.exports=r,r.ref=A.ref,r.atom=A.atom,r.error=A.error,r.pathValue=A.pathValue,r.prototype.constructor=r,r.prototype._materialized=!1,r.prototype._boxed=!1,r.prototype._progressive=!1,r.prototype._treatErrorsAsValues=!1,r.prototype._maxSize=Math.pow(2,53)-1,r.prototype._collectRatio=.75,r.prototype.get=t(71),r.prototype._getWithPaths=t(70),r.prototype.set=function(){var t=k(arguments,D,"set");return t!==!0?new u(function(e){e.onError(t)}):this._set.apply(this,arguments)},r.prototype.preload=function(){var t=k(arguments,q,"preload");if(t!==!0)return new u(function(e){e.onError(t)});var e=Array.prototype.slice.call(arguments),n=this;return new u(function(t){return n.get.apply(n,e).subscribe(function(){},function(e){t.onError(e)},function(){t.onCompleted()})})},r.prototype._set=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(w(r)?n-=1:r=void 0,t=new Array(n);++e<n;)t[e]=arguments[e];return a.create(this,t,r)},r.prototype.call=function(){var t,e=-1,n=arguments.length;for(t=new Array(n);++e<n;){var r=arguments[e];t[e]=r;var o=typeof r;if(e>1&&!Array.isArray(r)||0===e&&!Array.isArray(r)&&"string"!==o||1===e&&!Array.isArray(r)&&!x(r))return new u(function(t){t.onError(new Error("Invalid argument"))})}return c.create(this,t)},r.prototype.invalidate=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(t=new Array(n);++e<n;)if(t[e]=b.fromPath(arguments[e]),"object"!=typeof t[e])throw new Error("Invalid argument");p.create(this,t,r).subscribe(O,function(t){throw t})},r.prototype.deref=t(5),r.prototype.getValue=t(16),r.prototype.setValue=t(79),r.prototype._getValueSync=t(24),r.prototype._setValueSync=t(80),r.prototype._derefSync=t(6),r.prototype.setCache=function(t){var e=this._root.cache;if(t!==e){var n=this._root,r=this._path;this._path=[],this._root.cache={},"undefined"!=typeof e&&y(n,n.expired,m(e),0),S(t)?C(this,[t]):_(t)?E(this,[t]):g(t)&&E(this,[{json:t}]),this._path=r}else"undefined"==typeof e&&(this._root.cache={});return this},r.prototype.getCache=function(){var t=v(arguments);if(0===t.length)return P(this._root.cache);var e=[{}],n=this._path;return j.getWithPathsAsJSONGraph(this,t,e),this._path=n,e[0].jsonGraph},r.prototype.getVersion=function(t){var e=t&&b.fromPath(t)||[];if(Array.isArray(e)===!1)throw new Error("Model#getVersion must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._getVersion(this,e)},r.prototype._syncCheck=function(t){if(Boolean(this._source)&&this._root.syncRefCount<=0&&this._root.unsafeMode===!1)throw new Error("Model#"+t+" may only be called within the context of a request selector.");return!0},r.prototype._clone=function(t){var e=new r(this);for(var n in t){var o=t[n];"delete"===o?delete e[n]:e[n]=o}return e.setCache=void 0,e},r.prototype.batch=function(t){var e=t;"number"==typeof e?e=new f(Math.round(Math.abs(e))):e&&e.schedule||(e=new h);var n=this._clone();return n._request=new s(n,e),n},r.prototype.unbatch=function(){var t=this._clone();return t._request=new s(t,new l),t},r.prototype.treatErrorsAsValues=function(){return this._clone({_treatErrorsAsValues:!0})},r.prototype.asDataSource=function(){return new i(this)},r.prototype._materialize=function(){return this._clone({_materialized:!0})},r.prototype._dematerialize=function(){return this._clone({_materialized:"delete"})},r.prototype.boxValues=function(){return this._clone({_boxed:!0})},r.prototype.unboxValues=function(){return this._clone({_boxed:"delete"})},r.prototype.withoutDataSource=function(){return this._clone({_source:"delete"})},r.prototype.toJSON=function(){return{$type:"ref",value:this._path}},r.prototype.getPath=function(){return d(this._path)},r.prototype._getBoundValue=t(13),r.prototype._getVersion=t(18),r.prototype._getValueSync=t(17),r.prototype._getPathValuesAsPathMap=j.getWithPathsAsPathMap,r.prototype._getPathValuesAsJSONG=j.getWithPathsAsJSONGraph,r.prototype._setPathValuesAsJSON=t(78),r.prototype._setPathValuesAsJSONG=t(78),r.prototype._setPathValuesAsPathMap=t(78),r.prototype._setPathValuesAsValues=t(78),r.prototype._setPathMapsAsJSON=t(77),r.prototype._setPathMapsAsJSONG=t(77),r.prototype._setPathMapsAsPathMap=t(77),r.prototype._setPathMapsAsValues=t(77),r.prototype._setJSONGsAsJSON=t(76),r.prototype._setJSONGsAsJSONG=t(76),r.prototype._setJSONGsAsPathMap=t(76),r.prototype._setJSONGsAsValues=t(76),r.prototype._setCache=t(77),r.prototype._invalidatePathValuesAsJSON=t(48),r.prototype._invalidatePathMapsAsJSON=t(47)},{100:100,102:102,116:116,13:13,130:130,134:134,14:14,16:16,17:17,18:18,19:19,24:24,3:3,4:4,47:47,48:48,49:49,5:5,55:55,6:6,61:61,63:63,64:64,65:65,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,84:84,88:88,96:96,98:98,99:99}],3:[function(t,e,n){function r(t){this._model=t._materialize().treatErrorsAsValues()}r.prototype.get=function(t){return this._model.get.apply(this._model,t)._toJSONG()},r.prototype.set=function(t){return this._model.set(t)._toJSONG()},r.prototype.call=function(t,e,n,r){var o=[t,e,n].concat(r);return this._model.call.apply(this._model,o)._toJSONG()},e.exports=r},{}],4:[function(t,e,n){function r(t){var e=t||{};this.syncRefCount=0,this.expired=e.expired||[],this.unsafeMode=e.unsafeMode||!1,this.collectionScheduler=e.collectionScheduler||new s,this.cache={},o(e.comparator)&&(this.comparator=e.comparator),o(e.errorSelector)&&(this.errorSelector=e.errorSelector),o(e.onChange)&&(this.onChange=e.onChange)}var o=t(96),i=t(91),s=t(74);r.prototype.errorSelector=function(t,e){return e},r.prototype.comparator=function(t,e){return i(t,"value")&&i(e,"value")?t.value===e.value&&t.$type===e.$type&&t.$expires===e.$expires:t===e},e.exports=r},{74:74,91:91,96:96}],5:[function(t,e,n){function r(t,e){var n,r=!1;try{++t._root.syncRefCount,n=t._derefSync(e)}catch(i){n=i,r=!0}finally{--t._root.syncRefCount}return r?o.Observable["throw"](n):o.Observable["return"](n)}var o=t(159),i=t(134);e.exports=function(t){for(var e=this,n=-1,s=arguments.length-1,u=new Array(s),a=i.fromPath(t);++n<s;)u[n]=i.fromPath(arguments[n+1]);if(0===s)throw new Error("Model#deref requires at least one value path.");return o.Observable.defer(function(){return r(e,a)}).flatMap(function(t){if(Boolean(t)){if(s>0){var n=o.Observable.of(t);return t.get.apply(t,u)["catch"](o.Observable.empty()).concat(n).last().flatMap(function(){return r(e,a)}).filter(function(t){return t})}return o.Observable["return"](t)}if(s>0){var i=u.map(function(t){return a.concat(t)});return e.get.apply(e,i).concat(o.Observable.defer(function(){return r(e,a)})).last().filter(function(t){return t})}return o.Observable.empty()})}},{134:134,159:159}],6:[function(t,e,n){var r=t(134),o=t(13),i=t(8),s=t(118);e.exports=function(t){var e=r.fromPath(t);if(!Array.isArray(e))throw new Error("Model#derefSync must be called with an Array path.");var n=o(this,this._path.concat(e),!1),u=n.path,a=n.value,c=n.found;if(c&&void 0!==a&&(a.$type!==s||void 0!==a.value)){if(a.$type)throw new i;return this._clone({_path:u})}}},{118:118,13:13,134:134,8:8}],7:[function(t,e,n){function r(){this.message=r.message,this.stack=(new Error).stack}r.prototype=new Error,r.prototype.name="BoundJSONGraphModelError",r.message="It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.",e.exports=r},{}],8:[function(t,e,n){function r(t,e){this.message=i,this.stack=(new Error).stack,this.boundPath=t,this.shortedPath=e}var o="InvalidModelError",i="The boundPath of the model is not valid since a value or error was found before the path end.";r.prototype=new Error,r.prototype.name=o,r.message=i,e.exports=r},{}],9:[function(t,e,n){function r(t){this.message="An exception was thrown when making a request.",this.stack=(new Error).stack,this.innerError=t}var o="InvalidSourceError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],10:[function(t,e,n){function r(){this.message="The allowed number of retries have been exceeded.",this.stack=(new Error).stack}var o="MaxRetryExceededError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],11:[function(t,e,n){function r(t,e,n,r,o,h,f){for(var l,d,v=n,y=o,b=r,m=0;;){if(0===m&&b[c]?(m=y.length,d=b[c]):(l=y[m++],d=v[l]),d){var g=d.$type,w=g&&d.value||d;if(m<y.length){if(g){v=d;break}v=d;continue}if(v=d,g&&u(d))break;if(b[c]||i(b,d),g===a){f?s(t,d,h,null,null,null,y,y.length,f):p(t,d),m=0,y=w,b=d,v=e;continue}break}v=void 0;break}if(m<y.length&&void 0!==v){for(var x=[],_=0;m>_;_++)x[_]=y[_];y=x}return[v,y]}var o=t(26),i=o.create,s=t(22),u=t(27),a=t(120),c=t(33),p=t(29).promote;e.exports=r},{120:120,22:22,26:26,27:27,29:29,33:33}],12:[function(t,e,n){var r=t(15),o=t(8),i=t(7);e.exports=function(t,e){return function(n,s,u){var a,c,p,h=u[0],f={values:u,optimizedPaths:[]},l=n._root.cache,d=n._path,v=l,y=d.length,b=[];if(y){if(e)return{criticalError:new i};if(v=r(n,d),v.$type)return{criticalError:new o(d,d)};for(a=[],c=0;y>c;++c)a[c]=d[c]}else a=[],y=0;for(c=0,p=s.length;p>c;c++)t(n,l,v,s[c],0,h,f,b,a,y,e);return f}}},{15:15,7:7,8:8}],13:[function(t,e,n){var r=t(17),o=t(8);e.exports=function(t,e,n){var i,s,u,a,c,p=e,h=e;for(i=t._boxed,n=t._materialized,s=t._treatErrorsAsValues,t._boxed=!0,t._materialized=void 0===n||n,t._treatErrorsAsValues=!0,u=r(t,p.concat(null),!0),t._boxed=i,t._materialized=n,t._treatErrorsAsValues=s,p=u.optimizedPath,a=u.shorted,c=u.found,u=u.value;p.length&&null===p[p.length-1];)p.pop();if(c&&a)throw new o(h,p);return{path:p,value:u,shorted:a,found:c}}},{17:17,8:8}],14:[function(t,e,n){function r(t){var e,n,r,o={},i=Object.keys(t);for(n=0,r=i.length;r>n;n++)e=i[n],s(e)||(o[e]=t[e]);return o}function o(t,e,n){Object.keys(t).filter(function(e){return!s(e)&&t[e]}).forEach(function(n){var s=t[n],u=e[n];if(u||(u=e[n]={}),s.$type){var a,c=s.value&&"object"==typeof s.value,p=!t[i];return a=c||p?r(s):s.value,void(e[n]=a)}o(s,u,n)})}var i=t(37),s=t(97);e.exports=function(t){var e={};return o(t,e),e}},{37:37,97:97}],15:[function(t,e,n){e.exports=function(t,e){for(var n=t._root.cache,r=-1,o=e.length;++r<o&&n&&!n.$type;)n=n[e[r]];return n}},{}],16:[function(t,e,n){var r=t(64),o=t(134);e.exports=function(t){for(var e=o.fromPath(t),n=0,i=e.length;++n<i;)if("object"==typeof e[n])return new r(function(t){t.onError(new Error("Paths must be simple paths"))});var s=this;return new r(function(t){return s.get(e).subscribe(function(n){for(var r=n.json,o=-1,i=e.length;r&&++o<i;)r=r[e[o]];t.onNext(r)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{134:134,64:64}],17:[function(t,e,n){var r=t(11),o=t(25),i=t(27),s=t(29).promote,u=t(120),a=t(118),c=t(119);e.exports=function(t,e,n){for(var p,h,f,l,d,v=t._root.cache,y=e.length,b=[],m=!1,g=!1,w=0,x=v,_=v,S=v,E=!0,C=!1;x&&y>w;){if(p=e[w++],null!==p&&(x=_[p],b[b.length]=p),!x){S=void 0,m=!0,E=!1;break}if(f=x.$type,f===a&&void 0===x.value){S=void 0,E=!1,m=y>w;break}if(y>w){if(f===u){if(i(x)){C=!0,S=void 0,E=!1;break}if(l=r(t,v,v,x,x.value),d=l[0],!d){S=void 0,x=void 0,E=!1;break}f=d.$type,x=d,b=l[1].slice(0)}if(f)break}else S=x;_=x}if(y>w&&!C){for(h=w;y>h;++h)if(null!==e[w]){g=!0;break}for(g?(m=!0,S=void 0):S=x,h=w;y>h;++h)null!==e[h]&&(b[b.length]=e[h])}if(S&&f&&(i(S)?S=void 0:s(t,S)),S&&f===c&&!t._treatErrorsAsValues)throw{path:w===y?e:e.slice(0,w),value:S.value};return S&&t._boxed?S=Boolean(f)&&!n?o(S):S:!S&&t._materialized?S={$type:a}:S&&(S=S.value),{value:S,shorted:m,optimizedPath:b,found:E}}},{11:11,118:118,119:119,120:120,25:25,27:27,29:29}],18:[function(t,e,n){var r=t(46);e.exports=function(t,e){var n=t._getValueSync({_boxed:!0,_root:t._root,_treatErrorsAsValues:t._treatErrorsAsValues},e,!0).value,o=n&&n[r];return null==o?-1:o}},{46:46}],19:[function(t,e,n){var r=t(12),o=t(31),i=r(o,!1),s=r(o,!0);e.exports={getValueSync:t(17),getBoundValue:t(13),getWithPathsAsPathMap:i,getWithPathsAsJSONGraph:s}},{12:12,13:13,17:17,31:31}],20:[function(t,e,n){var r=t(29),o=t(25),i=r.promote;e.exports=function(t,e,n,r,s){var u=e.value;s.errors||(s.errors=[]),t._boxed&&(u=o(e)),s.errors.push({path:r.slice(0,n+1),value:u}),i(t,e)}},{25:25,29:29}],21:[function(t,e,n){function r(t,e,n,r,o,i,s){s.requestedMissingPaths.push(r.slice(0,n).concat(e)),s.optimizedMissingPaths.push(o.slice(0,i).concat(e))}var o=t(30),i=o.fastCopy;e.exports=function(t,e,n,o,s,u,a){var c;o.requestedMissingPaths||(o.requestedMissingPaths=[],o.optimizedMissingPaths=[]),c=n<e.length?i(e,n):[],r(t,c,n,s,u,a,o)}},{30:30}],22:[function(t,e,n){var r=t(29),o=t(25),i=r.promote,s=t(120),u=t(118),a=t(119),c=t(37);e.exports=function(t,e,n,r,p,h,f,l,d,v){if(n){var y,b,m,g,w,x,_,S,E=!1;if(e&&i(t,e),e&&void 0!==e.value||(E=t._materialized),E)S={$type:u};else if(t._boxed)S=o(e);else if(e.$type===s||e.$type===a)S=d?o(e):e.value;else if(d){var C=e.value&&"object"==typeof e.value,A=!e[c];S=C||A?o(e):e.value}else S=e.value;if(p&&(p.hasValue=!0),d){for(w=n.jsonGraph,w||(w=n.jsonGraph={},n.paths=[]),y=0,b=l-1;b>y;y++)g=f[y],w[g]||(w[g]={}),w=w[g];g=f[y],w[g]=E?{$type:u}:S,h&&n.paths.push(h.slice(0,r))}else if(0===r)n.json=S;else{for(w=n.json,w||(w=n.json={}),y=0;r-1>y;y++)m=h[y],w[m]||(w[m]={}),x=w,_=m,w=w[m];m=h[y],null!==m?w[m]=S:x[_]=S}}}},{118:118,119:119,120:120,25:25,29:29,37:37}],23:[function(t,e,n){var r=t(27),o=t(26),i=t(29),s=o.remove,u=i.splice,a=t(119),c=t(20),p=t(22),h=t(21),f=t(28),l=t(35);e.exports=function(t,e,n,o,i,d,v,y,b,m,g){var w=e&&e.$type,x=e&&void 0===e.value;return e&&w?void(r(e)?(e[l]||(u(t,e),s(e)),h(t,n,o,d,v,y,b)):w===a?(g&&(v[o]=null),m||t._treatErrorsAsValues?p(t,e,i,o,d,v,y,b,m,g):c(t,e,o,v,d)):(g&&(v[o]=null),(!x||x&&t._materialized)&&p(t,e,i,o,d,v,y,b,m,g))):void(f(t)?p(t,e,i,o,d,v,y,b,m,g):h(t,n,o,d,v,y,b))}},{119:119,20:20,21:21,22:22,26:26,27:27,28:28,29:29,35:35}],24:[function(t,e,n){var r=t(134);e.exports=function(t){var e=r.fromPath(t);if(Array.isArray(e)===!1)throw new Error("Model#getValueSync must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._syncCheck("getValueSync")&&this._getValueSync(this,e).value}},{134:134}],25:[function(t,e,n){var r=t(40);e.exports=function(t){var e,n,o,i=Object.keys(t);for(e={},n=0,o=i.length;o>n;n++){var s=i[n];s[0]!==r&&(e[s]=t[s])}return e}},{40:40}],26:[function(t,e,n){function r(t,e){var n=e[a]||0;e[i+n]=t,e[a]=n+1,t[u]=n,t[s]=e}function o(t){var e=t[s];if(e){for(var n=t[u],r=e[a];r>n;)e[i+n]=e[i+n+1],++n;e[a]=r-1,t[s]=void 0,t[u]=void 0}}var i=t(43),s=t(33),u=t(42),a=t(44);e.exports={create:r,remove:o}},{33:33,42:42,43:43,44:44}],27:[function(t,e,n){var r=t(106);e.exports=function(t){var e=void 0===t.$expires&&-1||t.$expires;return-1!==e&&1!==e&&(0===e||e<r())}},{106:106}],28:[function(t,e,n){e.exports=function(t){return t._materialized&&!t._source}},{}],29:[function(t,e,n){function r(t,e){var n=t._root,r=n[i];if(r!==e){var o=e[a],s=e[u];s&&(s[a]=o),o&&(o[u]=s),e[a]=void 0,n[i]=e,e[u]=r,r[a]=e}}function o(t,e){var n=t._root,r=e[a],o=e[u];o&&(o[a]=r),r&&(r[u]=o),e[a]=void 0,e===n[i]&&(n[i]=void 0),e===n[s]&&(n[s]=void 0),e[c]=!0,n.expired.push(e)}var i=t(34),s=t(45),u=t(38),a=t(41),c=t(35);e.exports={promote:r,splice:o}},{34:34,35:35,38:38,41:41,45:45}],30:[function(t,e,n){function r(t,e){var n,r,o,i=[];for(r=0,o=e||0,n=t.length;n>o;r++,o++)i[r]=t[o];return i}function o(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)null!==e[o]&&(i[n++]=e[o]);return i}function i(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)i[n++]=e[o];return i}e.exports={fastCat:i,fastCatSkipNulls:o,fastCopy:r}},{}],31:[function(t,e,n){var r=t(11),o=t(23),i=t(27),s=t(143).iterateKeySet,u=t(120),a=t(29).promote;e.exports=function c(t,e,n,p,h,f,l,d,v,y,b,m){var g=m,w=v;if(!n||n&&n.$type||h===p.length)return void o(t,n,p,h,f,l,d,w,y,b,g);var x,_;x=p[h];var S="object"==typeof x,E=h+1,C=!1,A=x;if(S&&(C={},A=s(x,C)),void 0!==A||!C.done){var N=y+1;do{g=!1;var k;null===A?k=n:(k=n[A],w[y]=A,d[h]=A);var O=w,P=N;if(k){var j=k.$type,D=j&&k.value||k;if(E<p.length&&j&&j===u&&!i(k)){b&&o(t,k,p,E,f,l,null,w,P,b,g),a(t,k);var q=r(t,e,e,k,D,f,b);g=!0,k=q[0];var R=q[1];for(O=[],P=R.length,_=0;P>_;++_)O[_]=R[_]}}c(t,e,k,p,E,f,l,d,O,P,b,g),C&&!C.done&&(A=s(x,C))}while(C&&!C.done)}}},{11:11,120:120,143:143,23:23,27:27,29:29}],32:[function(t,e,n){"use strict";function r(t){return new r.Model(t)}"function"==typeof Promise?r.Promise=Promise:r.Promise=t(151),e.exports=r,r.Model=t(2)},{151:151,2:2}],33:[function(t,e,n){e.exports=t(40)+"context"},{40:40}],34:[function(t,e,n){e.exports=t(40)+"head"},{40:40}],35:[function(t,e,n){e.exports=t(40)+"invalidated"},{40:40}],36:[function(t,e,n){e.exports=t(40)+"key"},{40:40}],37:[function(t,e,n){e.exports="$modelCreated"},{}],38:[function(t,e,n){e.exports=t(40)+"next"},{40:40}],39:[function(t,e,n){e.exports=t(40)+"parent"},{40:40}],40:[function(t,e,n){e.exports=String.fromCharCode(30)},{}],41:[function(t,e,n){e.exports=t(40)+"prev"},{40:40}],42:[function(t,e,n){e.exports=t(40)+"ref-index"},{40:40}],43:[function(t,e,n){e.exports=t(40)+"ref"},{40:40}],44:[function(t,e,n){e.exports=t(40)+"refs-length"},{40:40}],45:[function(t,e,n){e.exports=t(40)+"tail"},{40:40}],46:[function(t,e,n){e.exports=t(40)+"version"},{40:40}],47:[function(t,e,n){function r(t,e,n,o,s,u,c,p,h,f){if(!_(t)&&!t.$type)for(var l in t)if(l[0]!==a&&"$"!==l[0]&&m(t,l)){var d=t[l],v=g(d)&&!d.$type,y=i(n,o,s,l,d,v,!1,u,c,p,h,f),w=y[0],x=y[1];w&&(v?r(d,e+1,n,x,w,u,c,p,h,f):A(w,x,l,p)&&C(x,b(w),p,u))}}function o(t,e,n,r,o,s,a,h){if(w(n))return S(n,o,s),[void 0,e];y(s,n);var d=n,v=n.value,b=e;if(n=n[p],null!=n)b=n[c]||e;else{var m=0,g=v.length-1;b=n=e;do{var x=v[m],E=g>m,C=i(e,b,n,x,t,E,!0,r,o,s,a,h);if(n=C[0],_(n))return C;b=C[1]}while(m++<g);if(d[p]!==n){var A=n[l]||0;n[l]=A+1,n[u+A]=d,d[p]=n,d[f]=A}}return[n,b]}function i(t,e,n,r,i,u,a,c,p,h,f,l){for(var v=n.$type;v===d;){var y=o(i,t,n,c,p,h,f,l);if(n=y[0],_(n))return y;e=y[1],v=n&&n.$type}if(void 0!==v)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(40),c=t(39),p=t(33),h=t(46),f=t(42),l=t(44),d=t(120),v=t(13),y=t(50),b=t(88),m=t(91),g=t(100),w=t(95),x=t(96),_=t(102),S=t(86),E=t(92),C=t(115),A=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=E(),u=n._comparator,a=n._errorSelector,p=t._path,f=n.cache,l=p.length?v(t,p).value:f,d=l[c]||f,y=f[h],b=-1,m=e.length;++b<m;){var g=e[b];r(g.json,0,f,d,l,s,i,o,u,a)}var w=f[h],_=n.onChange;x(_)&&y!==w&&_()}},{100:100,102:102,109:109,115:115,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,88:88,91:91,92:92,95:95,96:96}],48:[function(t,e,n){function r(t,e,n,o,s,u,a,c){var p={},h=e<t.length-1,f=t[e],l=x(f,p);do{var d=i(n,o,s,l,h,!1,u,a,c),v=d[0],b=d[1];v&&(h?r(t,e+1,n,b,v,u,a,c):E(v,b,l,c)&&S(b,y(v),c,u)),l=x(f,p)}while(!p.done)}function o(t,e,n,r,o){if(b(e))return w(e,r,o),[void 0,t];v(o,e);var s=e,p=e.value,l=t;if(e=e[c],null!=e)l=e[a]||t;else{var d=0,y=p.length-1;l=e=t;do{var m=p[d],x=y>d,_=i(t,l,e,m,x,!0,n,r,o);if(e=_[0],g(e))return _;l=_[1]}while(d++<y);if(s[c]!==e){var S=e[f]||0;e[f]=S+1,e[u+S]=s,s[c]=e,s[h]=S}}return[e,l]}function i(t,e,n,r,i,u,a,c,p){for(var h=n.$type;h===l;){var f=o(t,n,a,c,p);if(n=f[0],g(n))return f;e=f[1],h=n.$type}if(void 0!==h)return[n,e];if(null==r){if(i)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(88),b=t(95),m=t(96),g=t(102),w=t(86),x=t(143).iterateKeySet,_=t(92),S=t(115),E=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=_(),u=t._path,c=n.cache,h=u.length?d(t,u).value:c,f=h[a]||c,l=c[p],v=-1,y=e.length;++v<y;){var b=e[v];r(b,0,c,f,h,s,i,o)}var g=c[p],w=n.onChange;m(w)&&l!==g&&w()}},{102:102,109:109,115:115,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,88:88,92:92,95:95,96:96}],49:[function(t,e,n){var r=t(36),o=t(39),i=t(34),s=t(45),u=t(38),a=t(41),c=t(108),p=t(115);e.exports=function(t,e,n,h,f,l){var d=n,v=f;"number"!=typeof v&&(v=.75);var y,b,m,g="number"==typeof l,w=h*v;for(b=e.pop();b;)m=b.$size||0,d-=m,g===!0?p(b,m,t,l):(y=b[o])&&c(b,y,b[r],t),b=e.pop();if(d>=h){var x=t[s];for(b=x;d>=w&&b;)x=x[a],m=b.$size||0,d-=m,g===!0&&p(b,m,t,l),b=x;t[s]=t[a]=b,null==b?t[i]=t[u]=void 0:b[u]=void 0}}},{108:108,115:115,34:34,36:36,38:38,39:39,41:41,45:45}],50:[function(t,e,n){var r=t(121),o=t(34),i=t(45),s=t(38),u=t(41),a=t(100);e.exports=function(t,e){if(a(e)&&e.$expires!==r){var n=t[o],c=t[i],p=e[s],h=e[u];e!==n&&(null!=p&&"object"==typeof p&&(p[u]=h),null!=h&&"object"==typeof h&&(h[s]=p),p=n,null!=n&&"object"==typeof n&&(n[u]=e),t[o]=t[s]=n=e,n[s]=p,n[u]=void 0),null!=c&&e!==c||(t[i]=t[u]=c=h||e)}return e}},{100:100,121:121,34:34,38:38,41:41,45:45}],51:[function(t,e,n){var r=t(34),o=t(45),i=t(38),s=t(41);e.exports=function(t,e){var n=t[r],u=t[o],a=e[i],c=e[s];null!=a&&"object"==typeof a&&(a[s]=c),null!=c&&"object"==typeof c&&(c[i]=a),e===n&&(t[r]=t[i]=a),e===u&&(t[o]=t[s]=c),e[i]=e[s]=void 0,n=u=a=c=void 0}},{34:34,38:38,41:41,45:45}],52:[function(t,e,n){function r(t,e){var n=!1;return function(){if(!n&&!t._disposed){n=!0,t._callbacks[e]=null,t._optimizedPaths[e]=[],t._requestedPaths[e]=[];var r=--t._count;0!==r||t.sent||(t._disposable.dispose(),t.requestQueue.removeRequest(t))}}}function o(t){for(var e=[],n=-1,r=0,o=t.length;o>r;++r)for(var i=t[r],s=0,u=i.length;u>s;++s)e[++n]=i[s];return e}var i=t(59),s=t(60),u=0,a=t(57).GetRequest,c=t(76),p=t(78),h=t(119),f=[],l=function(t,e){this.sent=!1,this.scheduled=!1,this.requestQueue=e,this.id=++u,this.type=a,this._scheduler=t,this._pathMap={},this._optimizedPaths=[],this._requestedPaths=[],this._callbacks=[],this._count=0,this._disposable=null,this._collapsed=null,this._disposed=!1};l.prototype={batch:function(t,e,n){var o=this,i=o._optimizedPaths,u=o._requestedPaths,a=o._callbacks,c=i.length;return i[c]=e,u[c]=t,a[c]=n,++o._count,o.scheduled||(o.scheduled=!0,o._disposable=o._scheduler.schedule(function(){s(o,i,function(t,e){if(o.requestQueue.removeRequest(o),o._disposed=!0,o._count){o._merge(u,t,e);for(var n=0,r=a.length;r>n;++n){var i=a[n];i&&i(t,e)}}})})),r(o,c)},add:function(t,e,n){var o,s,u=this,a=i(t,e,u._pathMap);a?(s=a[2],o=a[1]):(s=t,o=e);var c=!1,p=!1;if(o.length<e.length){c=!0;var h=u._callbacks.length;u._callbacks[h]=n,u._requestedPaths[h]=a[0],u._optimizedPaths[h]=[],++u._count,p=r(u,h)}return[c,s,o,p]},_merge:function(t,e,n){var r=this,i=r.requestQueue.model,s=i._root,u=s.errorSelector,a=s.comparator,l=i._path;i._path=f;var d=o(t);if(e){var v=e;v instanceof Error&&(v={message:v.message}),v.$type||(v={$type:h,value:v});var y=d.map(function(t){return{path:t,value:v}});p(i,y,null,u,a)}else c(i,[{paths:d,jsonGraph:n.jsonGraph}],null,u,a);i._path=l}},e.exports=l},{119:119,57:57,59:59,60:60,76:76,78:78}],53:[function(t,e,n){function r(){this.length=0,this.pending=!1,this.pathmaps=[],s.call(this,this._subscribe)}var o=t(159),i=o.Observer,s=o.Observable,u=o.Disposable,a=o.SerialDisposable,c=o.CompositeDisposable,p=t(9),h=t(143),f=h.iterateKeySet;r.create=function(t,e,n){var r=new this;return r.queue=t,r.model=e,r.index=n,r},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.insertPath=function(t,e,n,r,o){var i=r||0,s=o||t.length-1,u=n||this.pathmaps[s+1]||(this.pathmaps[s+1]=Object.create(null));if(void 0===u||null===u)return!1;var a,c,p=t[i],h={};a=f(p,h);do{if(c=u[a],s>i){if(null==c){if(e)return!1;c=u[a]=Object.create(null)}if(this.insertPath(t,e,c,i+1,s)===!1)return!1}else u[a]=(c||0)+1,this.length+=1;h.done||(a=f(p,h))}while(!h.done);return!0},r.prototype.removePath=function(t,e,n,r){var o=n||0,i=r||t.length-1,s=e||this.pathmaps[i+1];if(void 0===s||null===s)return!0;var u,a,c=0,p=t[o],h={};u=f(p,h);do if(a=s[u],void 0!==a&&null!==a){if(i>o){c+=this.removePath(t,a,o+1,i);var l=void 0;for(l in a)break;void 0===l&&delete s[u]}else a=s[u]=(a||1)-1,0===a&&delete s[u],c+=1,this.length-=1;h.done||(u=f(p,h))}while(!h.done);return c},r.prototype.getSourceObserver=function(t){var e=this;return i.create(function(n){n.jsonGraph=n.jsonGraph||n.jsong||n.values||n.value,n.index=e.index,t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})},r.prototype._subscribe=function(t){var e=this,n=this.queue;e.pending=!0;var r=!1,o=new a,i=u.create(function(){r||(r=!0,n&&n._remove(e))}),s=new c(o,i);try{o.setDisposable(this.model._source[this.method](this.getSourceArgs()).subscribe(this.getSourceObserver(t)))}catch(h){throw new p(h)}return s},e.exports=r},{143:143,159:159,9:9}],54:[function(t,e,n){function r(t,e){this.total=0,this.model=t,this.requests=[],this.scheduler=e}var o=t(58),i=t(40),s=t(90),u=t(100),a=t(143);r.prototype.set=function(t){return t.paths=a.collapse(t.paths),o.create(this.model,t)},r.prototype._remove=function(t){var e=this.requests,n=e.indexOf(t);-1!==n&&e.splice(n,1)},r.prototype.distributePaths=function(t,e,n){var r,o,i=this.model,s=-1,u=t.length,a=-1,c=e.length,p=[];t:for(;++s<u;){var h=t[s];for(a=-1;++a<c;)if(o=e[a],o.insertPath(h,o.pending)){p[a]=o;continue t}r||(r=n.create(this,i,this.total++),e[a]=r,p[c++]=r),r.insertPath(h,!1)}var f=[],l=-1;for(a=-1;++a<c;)o=p[a],null!=o&&(f[++l]=o);return f},r.prototype.mergeJSONGraphs=function(t,e){var n=0,r=[],o=[],a=[],c=t.index,p=e.index;t.index=Math.max(c,p),r[-1]=t.jsonGraph||{},o[-1]=e.jsonGraph||{};t:for(;n>-1;){for(var h=r[n-1],f=o[n-1],l=a[n-1]||(a[n-1]=Object.keys(f));l.length>0;){var d=l.pop();if(d[0]!==i)if(h.hasOwnProperty(d)){var v=h[d],y=s(v),b=f[d],m=s(b);if(u(v)&&u(b)&&!y&&!m){r[n]=v,o[n]=b,n+=1;continue t}p>c&&(h[d]=b)}else h[d]=f[d]}n-=1}return t},e.exports=r},{100:100,143:143,40:40,58:58,90:90}],55:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(54),i=t(56);r.prototype.get=i.prototype.get,r.prototype.removeRequest=i.prototype.removeRequest,r.prototype.set=o.prototype.set,r.prototype.call=o.prototype.call,e.exports=r},{54:54,56:56}],56:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(57),i=t(52);r.prototype={setScheduler:function(t){this.scheduler=t},get:function(t,e,n){function r(){v||(--h,0===h&&n())}var s,u,a,c=this,p=[],h=0,f=c._requests,l=e,d=t,v=!1;for(s=0,u=f.length;u>s;++s)if(a=f[s],a.type===o.GetRequest){if(a.sent){var y=a.add(d,l,r);y[0]&&(d=y[1],l=y[2],p[p.length]=y[3],++h)}else a.batch(d,l,r),l=[],d=[],++h;if(!l.length)break}if(l.length){a=new i(c.scheduler,c),f[f.length]=a,++h;var b=a.batch(d,l,r);p[p.length]=b}return function(){if(!v&&0!==h){v=!0;for(var t=p.length,e=0;t>e;++e)p[e]()}}},removeRequest:function(t){for(var e=this._requests,n=e.length;--n>=0;)if(e[n].id===t.id){e.splice(n,1);break}}},e.exports=r},{52:52,57:57}],57:[function(t,e,n){e.exports={GetRequest:"GET"}},{}],58:[function(t,e,n){function r(){s.call(this)}var o=t(159),i=o.Observer,s=t(53),u=t(83),a=t(76),c=t(78),p=new Array(0);r.create=function(t,e){var n=new r;return n.model=t,n.jsonGraphEnvelope=e,n},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.method="set",r.prototype.insertPath=function(){return!1},r.prototype.removePath=function(){return 0},r.prototype.getSourceArgs=function(){return this.jsonGraphEnvelope},r.prototype.getSourceObserver=function(t){var e=this.model,n=e._path,r=this.jsonGraphEnvelope.paths,o=e._root,h=o.errorSelector,f=o.comparator;return s.prototype.getSourceObserver.call(this,i.create(function(o){e._path=p;var i=a(e,[{paths:r,jsonGraph:o.jsonGraph}],null,h,f);o.paths=i[1],e._path=n,t.onNext(o)},function(o){e._path=p,c(e,u(r,function(t){return{path:t,value:o}}),null,h,f),e._path=n,t.onError(o)},function(){t.onCompleted()}))},e.exports=r},{159:159,53:53,76:76,78:78,83:83}],59:[function(t,e,n){var r=t(143).hasIntersection,o=t(84);e.exports=function(t,e,n){for(var i=[],s=[],u=[],a=-1,c=-1,p=!1,h=0,f=e.length;f>h;++h){var l=e[h],d=n[l.length];d&&r(d,l,0)?(!p&&h>0&&(s=o(t,0,h),i=o(e,0,h)),u[++a]=t[h],p=!0):p&&(i[++c]=l,s[c]=t[h])}return p?[u,i,s]:null}},{143:143,84:84}],60:[function(t,e,n){var r=t(143),o=r.toTree,i=r.toPaths;e.exports=function(t,e,n){if(0===t._count)return void t.requestQueue.removeRequest(t);t.sent=!0,t.scheduled=!1;for(var r=t._pathMap,s=Object.keys(e),u=0,a=s.length;a>u;++u)for(var c=e[u],p=0,h=c.length;h>p;++p){var f=c[p],l=f.length;if(r[l]){var d=r[l];d[d.length]=f}else r[l]=[f]}for(var v=Object.keys(r),y=0,b=v.length;b>y;++y){var m=v[y];r[m]=o(r[m])}var g,w=t._collasped=i(r);t.requestQueue.model._source.get(w).subscribe(function(t){g=t},function(t){n(t,g)},function(){n(null,g)})}},{143:143}],61:[function(t,e,n){function r(t){u.call(this,t||i)}function o(t){return s.Observable.defer(function(){return t})}function i(t){function e(t){function e(t,e){if(Boolean(e.invalidated))t.invalidations.push(t.localThisPath.concat(e.path));else{var n=e.path,r=e.value;Boolean(r)&&"object"==typeof r&&r.$type===f?t.references.push({path:i(n),value:e.value}):t.values.push({path:i(n),value:e.value})}return t}function n(t){var e=t.values.concat(t.references);return e.length>0?o(g.set.apply(g,e)._toJSONG()).map(function(e){return{results:t,envelope:e}}):u["return"]({results:t,envelope:{jsonGraph:{},paths:[]}})}function r(t){var e,n=t.envelope,r=t.results,c=r.values,p=r.references,h=r.invalidations,f=c.map(a).map(i),l=p.reduce(s,[]),d=b.map(i),v=l.concat(d);return e=v.length>0?o(m.get.apply(m,f.concat(v))._toJSONG()):u["return"](n),e.doAction(function(t){t.invalidated=h})}function s(t,e){var n=e.path;return t.push.apply(t,y.map(function(t){return n.concat(t)})),t}function a(t){return t.path}var c=t&&t.localFn;if("function"==typeof c){var p=t.model,h=p._path,l=c.apply(p,v).reduce(e,{values:[],references:[],invalidations:[],localThisPath:h}).flatMap(n).flatMap(r);return u["return"](l)}return u.empty()}function n(t){function e(t){var e=t.invalidated;return e&&e.length&&m.invalidate.apply(m,e),t}return t&&"object"==typeof t?s.Observable.defer(function(){
3456 var e;try{e=t.call(x,v,y,b)}catch(n){e=u["throw"](new p(n))}return e}).map(e):u.empty()}function r(t){return o(g.set(t)).reduce(function(t){return t},null).map(function(){return{invalidated:t.invalidated,paths:t.paths.map(function(t){return t.slice(w.length)})}})}function i(t){return _.concat(t)}var c=this.args,l=this.model,d=h.fromPath(c[0]),v=c[1]||[],y=(c[2]||[]).map(h.fromPath),b=(c[3]||[]).map(h.fromPath),m=l._clone({_path:[]}),g=m.withoutDataSource(),w=l._path,x=w.concat(d),_=x.slice(0,-1),S=o(l.withoutDataSource().get(d)).map(function(t){for(var e=t.json,n=-1,r=d.length;e&&++n<r;)e=e[d[n]];var o=m._derefSync(_).boxValues();return{model:o,localFn:e}}).flatMap(e).defaultIfEmpty(n(l._source)).mergeAll().flatMap(r),E=new a;return E.add(S.subscribe(function(e){var n=e.paths,r=e.invalidated,i=l.get.apply(l,n);"AsJSONG"===t.outputFormat&&(i=o(i._toJSONG()).doAction(function(t){t.invalidated=r})),E.add(i.subscribe(t))},function(e){t.onError(e)})),E}var s=t(159)&&t(158),u=s.Observable,a=s.CompositeDisposable,c=t(64),p=t(9),h=t(134),f=t(120);r.create=c.create,r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){return this},r.prototype.initialize=function(){return this},e.exports=r},{120:120,134:134,158:158,159:159,64:64,9:9}],62:[function(t,e,n){function r(t){i.call(this,t)}var o=t(159),i=o.Observable,s=t(64),u=t(134),a=t(88),c=t(49),p=t(81),h=t(46),f=Array.isArray,l=t(101),d=t(98),v=t(99);r.create=s.create,r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.subscribeCount=0,r.prototype.subscribeLimit=10,r.prototype.initialize=function(){for(var t,e,n=this.model,r=this.outputFormat||"AsPathMap",o=this.isProgressive,i=[{}],s=[],a=this.args,c=-1,h=a.length;++c<h;){var y,b=a[c];f(b)||"string"==typeof b?(b=u.fromPath(b),y="PathValues"):l(b)?(b.path=u.fromPath(b.path),y="PathValues"):v(b)?y="JSONGs":d(b)&&(y="PathMaps"),e!==y&&(e=y,t={inputType:y,arguments:[]},s.push(t),t.values=i),t.arguments.push(b)}return this.boundPath=p(n._path),this.groups=s,this.outputFormat=r,this.isProgressive=o,this.isCompleted=!1,this.isMaster=null==n._source,this.values=i,this},r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){var e=this["finally"](function(){var e=t._root,n=e.cache;e.collectionScheduler.schedule(function(){c(e,e.expired,a(n),t._maxSize,t._collectRatio,n[h])})});return new this.constructor(function(t){return e.subscribe(t)})},e.exports=r},{101:101,134:134,159:159,46:46,49:49,64:64,81:81,88:88,98:98,99:99}],63:[function(t,e,n){function r(t){u.call(this,t||o)}function o(t){for(var e=this.model,n=this.method,r=this.groups,o=-1,i=r.length;++o<i;){var u=r[o],a=u.inputType,c=u.arguments;if(c.length>0){var p="_"+n+a+"AsJSON",h=e[p];h(e,c)}}return t.onCompleted(),s.empty}var i=t(159),s=i.Disposable,u=t(62);r.create=u.create,r.prototype=Object.create(u.prototype),r.prototype.method="invalidate",r.prototype.constructor=r,e.exports=r},{159:159,62:62}],64:[function(t,e,n){function r(t){this._subscribe=t}function o(t){var e=this.model,n=new this.type;return n.model=e,n.args=this.args,n.outputFormat=t.outputFormat||"AsPathMap",n.isProgressive=t.isProgressive||!1,n.subscribeCount=0,n.subscribeLimit=t.retryLimit||10,n.initialize().invokeSourceRequest(e).ensureCollect(e).subscribe(t)}var i=t(32),s=t(159)&&t(158),u=s.Observable,a=t(84),c=t(105),p={outputFormat:{value:"AsJSONG"}},h={isProgressive:{value:!0}};r.create=function(t,e){var n=new r(o);return n.args=e,n.type=this,n.model=t,n},r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype._mixin=function(){var t=this,e=a(arguments);return new t.constructor(function(n){return t.subscribe(e.reduce(function(t,e){return Object.create(t,e)},n))})},r.prototype._toJSONG=function(){return this._mixin(p)},r.prototype.progressively=function(){return this._mixin(h)},r.prototype.subscribe=function(t,e,n){var r=t;r&&"object"==typeof r||(r={onNext:t||c,onError:e||c,onCompleted:n||c});var o=this._subscribe(r);switch(typeof o){case"function":return{dispose:o};case"object":return o||{dispose:c};default:return{dispose:c}}},r.prototype.then=function(t,e){var n=this;return new i.Promise(function(t,e){var r,o=!1;n.toArray().subscribe(function(t){r=t.length<=1?t[0]:t},function(t){o=!0,e(t)},function(){o===!1&&t(r)})}).then(t,e)},e.exports=r},{105:105,158:158,159:159,32:32,84:84}],65:[function(t,e,n){function r(t){l.call(this,t||o)}function o(t){return this.isCompleted?s.call(this,t):i.call(this,t)}function i(t){if(this.subscribeCount++>this.subscribeLimit)return t.onError("Loop kill switch thrown."),h.empty;for(var e=[],n=[],r=this.model,o=this.isMaster,i=r._root,c=this.outputFormat,p=i.errorSelector,f=this.method,l=this.groups,d=-1,y=l.length;++d<y;){var b=l[d],m=b.inputType,g=b.arguments;if(g.length>0){var w="_"+f+m+c,x=r[w],_=x(r,g,null,p);n.push.apply(n,_[1]),"PathValues"===m?e.push.apply(e,g.map(u)):"JSONGs"===m?e.push.apply(e,v(g,a)):e.push.apply(e,_[0])}}return this.requestedPaths=e,o?(this.isCompleted=!0,s.call(this,t)):void t.onError({method:f,optimizedPaths:n,invokeSourceRequest:!0})}function s(t){var e=new f(this.model,this.requestedPaths);return"AsJSONG"===this.outputFormat&&(e=e._toJSONG()),this.isProgressive&&(e=e.progressively()),e.subscribe(t)}function u(t){return t.path}function a(t){return t.paths}var c=t(159),p=c.Observable,h=c.Disposable,f=t(67),l=t(62),d=t(9),v=t(82),y=new Array(0);r.create=l.create,r.prototype=Object.create(l.prototype),r.prototype.method="set",r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){var e=this,n=this["catch"](function(r){var o;if(r&&r.invokeSourceRequest===!0){var i={},s=t._path,u=r.optimizedPaths;t._path=y,t._getPathValuesAsJSONG(t._materialize().withoutDataSource(),u,[i]),t._path=s,o=t._request.set(i)["do"](function(t){e.isCompleted=u.length===t.paths.length},function(){e.isCompleted=!0}).materialize().flatMap(function(t){if("C"===t.kind)return p.empty();if("E"===t.kind){var e=t.exception;if(d.is(e))return p["throw"](t.exception)}return n})}else o=p["throw"](r);return o});return new this.constructor(function(t){return n.subscribe(t)})},e.exports=r},{159:159,62:62,67:67,82:82,9:9}],66:[function(t,e,n){var r=function(t){this.disposed=!1,this.currentDisposable=t};r.prototype={dispose:function(){if(!this.disposed&&this.currentDisposable){this.disposed=!0;var t=this.currentDisposable;t.dispose?t.dispose():t()}}},e.exports=r},{}],67:[function(t,e,n){var r=t(64),o=t(68),i=t(69),s={dispose:function(){}},u=t(159).Observable,a=e.exports=function(t,e,n,r){this.model=t,this.currentRemainingPaths=e,this.isJSONGraph=n||!1,this.isProgressive=r||!1};a.prototype=Object.create(u.prototype),a.prototype.subscribe=r.prototype.subscribe,a.prototype.then=r.prototype.then,a.prototype._toJSONG=function(){return new a(this.model,this.currentRemainingPaths,!0,this.isProgressive)},a.prototype.progressively=function(){return new a(this.model,this.currentRemainingPaths,this.isJSONGraph,!0)},a.prototype._subscribe=function(t){var e=[{}],n=[],r=t.isJSONG=this.isJSONGraph,u=this.isProgressive,a=o(this.model,this.currentRemainingPaths,t,u,r,e,n);return a?i(this,this.model,a,t,e,n,1):s}},{159:159,64:64,68:68,69:69}],68:[function(t,e,n){var r=t(19),o=r.getWithPathsAsJSONGraph,i=r.getWithPathsAsPathMap;e.exports=function(t,e,n,r,s,u,a){var c;if(c=s?o(t,e,u):i(t,e,u),c.criticalError)return n.onError(c.criticalError),null;var p=c.hasValue,h=!c.requestedMissingPaths||!t._source,f=u[0].json||u[0].jsonGraph;if(c.errors)for(var l=c.errors,d=a.length,v=0,y=l.length;y>v;++v,++d)a[d]=l[v];if(p&&r||f&&h)try{++t._root.syncRefCount,n.onNext(u[0])}catch(b){throw b}finally{--t._root.syncRefCount}return h?(a.length?n.onError(a):n.onCompleted(),null):c}},{19:19}],69:[function(t,e,n){var r=t(68),o=t(10),i=t(30).fastCat,s=t(49),u=t(88),a=t(66),c=t(46);e.exports=function p(t,e,n,h,f,l,d){if(10===d)throw new o;var v=e._request,y=n.requestedMissingPaths,b=n.optimizedMissingPaths,m=new a,g=[],w=e._path;if(w.length)for(var x=0,_=y.length;_>x;++x)g[x]=i(w,y[x]);else g=y;var S=v.get(g,b,function(){var n=r(e,y,h,t.isProgressive,t.isJSONGraph,f,l);if(n)m.currentDisposable=p(t,e,n,h,f,l,d+1);else{var o=e._root,i=o.cache,a=i[c];s(o,o.expired,u(i),e._maxSize,e._collectRatio,a)}});return m.currentDisposable=S,m}},{10:10,30:30,46:46,49:49,66:66,68:68,88:88}],70:[function(t,e,n){var r=t(67);e.exports=function(t){return new r(this,t)}},{67:67}],71:[function(t,e,n){var r=t(134),o=t(64),i=t(72),s=t(116),u=t(67);e.exports=function(){var t=s(arguments,i,"get");if(t!==!0)return new o(function(e){e.onError(t)});var e=r.fromPathsOrPathValues(arguments);return new u(this,e)}},{116:116,134:134,64:64,67:67,72:72}],72:[function(t,e,n){e.exports={path:!0,pathSyntax:!0}},{}],73:[function(t,e,n){function r(){}var o=t(123),i=t(159),s=i.Disposable;r.prototype.schedule=function(t){return o(t),s.empty},r.prototype.scheduleWithState=function(t,e){var n=this;return o(function(){e(n,t)}),s.empty},e.exports=r},{123:123,159:159}],74:[function(t,e,n){function r(){}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){return t(),i.empty},r.prototype.scheduleWithState=function(t,e){return e(this,t),i.empty},e.exports=r},{159:159}],75:[function(t,e,n){function r(t){this.delay=t}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){var e=setTimeout(t,this.delay);return i.create(function(){void 0!==e&&(clearTimeout(e),e=void 0)})},r.prototype.scheduleWithState=function(t,e){var n=this,r=setTimeout(function(){e(n,t)},this.delay);return i.create(function(){void 0!==r&&(clearTimeout(r),r=void 0)})},e.exports=r},{159:159}],76:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,d,v,y,b,g,w){for(var x={},_=e<t.length-1,S=t[e],E=m(S,x),C=d.index;;){f.depth=e;var A=i(n,o,s,u,a,c,E,_,!1,f,d,v,y,b,g,w);f[e]=E,f.index=e,d[d.index++]=E;var N=A[0],k=A[1];if(N&&(_?r(t,e+1,n,k,N,u,A[3],A[2],p,h,f,d,v,y,b,g,w):(l(b,N),p.push(f.slice(0,f.index+1)),h.push(d.slice(0,d.index)))),E=m(S,x),x.done)break;d.index=C}}function o(t,e,n,r,o,s,c,f,v,m,g){var w=e.value;if(s.splice(0,s.length),s.push.apply(s,w),d(e))return s.index=w.length,b(e,f,v),[void 0,t,r,n];l(v,e);var x=0,_=e,S=w.length-1,E=e=t,C=r=n;do{var A=w[x],N=S>x,k=i(t,E,e,n,C,r,A,N,!0,o,s,c,f,v,m,g);if(e=k[0],y(e))return s.index=x,k;E=k[1],r=k[2],C=k[3]}while(x++<S);if(s.index=x,_[a]!==e){var O=e[h]||0;e[h]=O+1,e[u+O]=_,_[a]=e,_[p]=O}return[e,E,r,C]}function i(t,e,n,r,i,u,a,c,p,h,l,d,v,b,m,g){for(var x=n.$type;x===f;){var _=o(t,n,r,u,h,l,d,v,b,m,g);if(n=_[0],y(n))return _;e=_[1],u=_[2],i=_[3],x=n.$type}if(void 0!==x)return[n,e,u,i];if(null==a){if(c)throw new Error("`null` is not allowed in branch key positions.");n&&(a=n[s])}else e=n,i=u,n=e[a],u=i&&i[a];return n=w(e,n,u,a,h,l,d,v,b,m,g),[n,e,u,i]}var s=t(36),u=t(43),a=t(33),c=t(46),p=t(42),h=t(44),f=t(120),l=t(50),d=t(94),v=t(96),y=t(102),b=t(86),m=t(143).iterateKeySet,g=t(92),w=t(103);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,p=g(),h=s.cache,f=h[c],l=[],d=[],y=[],b=[],m=-1,w=e.length;++m<w;)for(var x=e[m],_=x.paths,S=x.jsonGraph,E=-1,C=_.length;++E<C;){var A=_[E];d.index=0,r(A,0,h,h,h,S,S,S,y,b,l,d,p,a,u,i,o)}var N=h[c],k=s.onChange;return v(k)&&f!==N&&k(),[y,b]}},{102:102,103:103,120:120,143:143,33:33,36:36,42:42,43:43,44:44,46:46,50:50,86:86,92:92,94:94,96:96}],77:[function(t,e,n){function r(t,e,n,o,u,a,c,p,h,f,l,d,v,y){var b=s(t);if(b&&b.length)for(var g=0,x=b.length,_=h.index;;){var S=b[g],E=t[S],C=w(E)&&!E.$type;p.depth=e;var A=i(n,o,u,S,E,C,!1,p,h,f,l,d,v,y);p[e]=S,p.index=e,h[h.index++]=S;var N=A[0],k=A[1];if(N&&(C?r(E,e+1,n,k,N,a,c,p,h,f,l,d,v,y):(m(d,N),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),++g>=x)break;h.index=_}}function o(t,e,n,r,o,s,u,c,f,v){var y=n.value;if(o.splice(0,o.length),o.push.apply(o,y),x(n))return o.index=y.length,E(n,u,c),[void 0,e];m(c,n);var b=n,g=e;if(n=n[h],null!=n)g=n[p]||e,o.index=y.length;else{var w=0,_=y.length-1;g=n=e;do{var C=y[w],A=_>w,N=i(e,g,n,C,t,A,!0,r,o,s,u,c,f,v);if(n=N[0],S(n))return o.index=w,N;g=N[1]}while(w++<_);if(o.index=w,b[h]!==n){var k=n[d]||0;n[d]=k+1,n[a+k]=b,b[h]=n,b[l]=k}}return[n,g]}function i(t,e,n,r,i,s,a,c,p,h,f,l,d,y){for(var b=n.$type;b===v;){var m=o(i,t,n,c,p,h,f,l,d,y);if(n=m[0],S(n))return m;e=m[1],b=n&&n.$type}if(void 0!==b)return[n,e];if(null==r){if(s)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[u])}else e=n,n=e[r];return n=A(e,n,r,i,s,a,c,p,h,f,l,d,y),[n,e]}function s(t){if(w(t)&&!t.$type){var e=[],n=0;b(t)&&(e[n++]="length");for(var r in t)r[0]!==c&&"$"!==r[0]&&g(t,r)&&(e[n++]=r);return e}}var u=t(36),a=t(43),c=t(40),p=t(39),h=t(33),f=t(46),l=t(42),d=t(44),v=t(120),y=t(13),b=Array.isArray,m=t(50),g=t(91),w=t(100),x=t(95),_=t(96),S=t(102),E=t(86),C=t(92),A=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,c=C(),h=t._path,l=s.cache,d=h.length?y(t,h).value:l,v=d[p]||l,b=l[f],m=[],g=[],w=[],x=h.length,S=-1,E=e.length;++S<E;){var A=e[S],N=h.slice(0);N.index=x,r(A.json,0,l,v,d,g,w,m,N,c,a,u,i,o)}var k=l[f],O=s.onChange;return _(O)&&b!==k&&O(),[g,w]}},{100:100,102:102,104:104,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,91:91,92:92,95:95,96:96}],78:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,l,d,y,b){for(var m={},g=n<e.length-1,x=e[n],_=w(x,m),S=h.index;;){p.depth=n;var E=i(o,s,u,_,t,g,!1,p,h,f,l,d,y,b);p[n]=_,p.index=n,h[h.index++]=_;var C=E[0],A=E[1];if(C&&(g?r(t,e,n+1,o,A,C,a,c,p,h,f,l,d,y,b):(v(d,C),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),_=w(x,m),m.done)break;h.index=S}}function o(t,e,n,r,o,s,p,l,d,b){var w=n.value;if(o.splice(0,o.length),o.push.apply(o,w),y(n))return o.index=w.length,g(n,p,l),[void 0,e];v(l,n);var x=n,_=e;if(n=n[c],null!=n)_=n[a]||e,o.index=w.length;else{var S=0,E=w.length-1;_=n=e;do{var C=w[S],A=E>S,N=i(e,_,n,C,t,A,!0,r,o,s,p,l,d,b);if(n=N[0],m(n))return o.index=S,N;_=N[1]}while(S++<E);if(o.index=S,x[c]!==n){var k=n[f]||0;n[f]=k+1,n[u+k]=x,x[c]=n,x[h]=k}}return[n,_]}function i(t,e,n,r,i,u,a,c,p,h,f,d,v,y){for(var b=n.$type;b===l;){var g=o(i,t,n,c,p,h,f,d,v,y);if(n=g[0],m(n))return g;e=g[1],b=n.$type}if(void 0!==b)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return n=_(e,n,r,i,u,a,c,p,h,f,d,v,y),[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(95),b=t(96),m=t(102),g=t(86),w=t(143).iterateKeySet,x=t(92),_=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,c=s.expired,h=x(),f=t._path,l=s.cache,v=f.length?d(t,f).value:l,y=v[a]||l,m=l[p],g=[],w=[],_=[],S=f.length,E=-1,C=e.length;++E<C;){var A=e[E],N=A.path,k=A.value,O=f.slice(0);O.index=S,r(k,N,0,l,y,v,w,_,g,O,h,c,u,i,o)}var P=l[p],j=s.onChange;return b(j)&&m!==P&&j(),[w,_]}},{102:102,104:104,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,92:92,95:95,96:96}],79:[function(t,e,n){var r=t(130),o=t(64),i=t(101);e.exports=function(t,e){for(var n=i(t)?t:r.pathValue(t,e),s=0,u=n.path,a=u.length;++s<a;)if("object"==typeof u[s])return new o(function(t){t.onError(new Error("Paths must be simple paths"))});var c=this;return new o(function(t){return c._set(n).subscribe(function(e){for(var n=e.json,r=-1,o=u.length;n&&++r<o;)n=n[u[r]];t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{101:101,130:130,64:64}],80:[function(t,e,n){var r=t(134),o=t(101),i=t(78);e.exports=function(t,e,n,s){var u=r.fromPath(t),a=e,c=n,p=s;if(o(u)?(p=c,c=a,a=u):a={path:u,value:a},o(a)===!1)throw new Error("Model#setValueSync must be called with an Array path.");return"function"!=typeof c&&(c=this._root._errorSelector),"function"!=typeof p&&(p=this._root._comparator),this._syncCheck("setValueSync")?(i(this,[a]),this._getValueSync(this,a.path).value):void 0}},{101:101,134:134,78:78}],81:[function(t,e,n){e.exports=function(t){if(!t)return t;for(var e=-1,n=t.length,r=[];++e<n;)r[e]=t[e];return r}},{}],82:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=-1,o=t.length,i=[];++r<o;)for(var s=e(t[r],r,t),u=-1,a=s.length;++u<a;)i[++n]=s[u];return i}},{}],83:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=t.length,o=new Array(r);++n<r;)o[n]=e(t[n],n,t);return o}},{}],84:[function(t,e,n){e.exports=function(t,e,n){var r=e||0,o=-1,i=t.length-r;0>i&&(i=0),n>0&&i>n&&(i=n);for(var s=new Array(i);++o<i;)s[o]=t[o+r];return s}},{}],85:[function(t,e,n){var r=t(40),o=t(91),i=Array.isArray,s=t(100);e.exports=function(t){var e=t;if(s(e)){e=i(t)?[]:{};var n=t;for(var u in n)u[0]!==r&&o(n,u)&&(e[u]=n[u])}return e}},{100:100,40:40,91:91}],86:[function(t,e,n){var r=t(51),o=t(35);e.exports=function(t,e,n){return t[o]||(t[o]=!0,e.push(t),r(n,t)),t}},{35:35,51:51}],87:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$expires||void 0}},{100:100}],88:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$size||0}},{100:100}],89:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$timestamp||void 0}},{100:100}],90:[function(t,e,n){var r=t(100);e.exports=function(t,e){var n=r(t)&&t.$type||void 0;return e&&n?"branch":n}},{100:100}],91:[function(t,e,n){var r=t(100),o=Object.prototype.hasOwnProperty;e.exports=function(t,e){return r(t)&&o.call(t,e)}},{100:100}],92:[function(t,e,n){var r=1;e.exports=function(){return r++}},{}],93:[function(t,e,n){var r=t(36),o=t(39),i=t(46);e.exports=function(t,e,n,s){return t[r]=n,t[o]=e,t[i]=s,e[n]=t,t}},{36:36,39:39,46:46}],94:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&e!==o&&e<r()}},{106:106,121:121,122:122}],95:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&(e===o||e<r())}},{106:106,121:121,122:122}],96:[function(t,e,n){var r="function";e.exports=function(t){return Boolean(t)&&typeof t===r}},{}],97:[function(t,e,n){var r=t(40);e.exports=function(t){return"$size"===t||t&&t.charAt(0)===r}},{40:40}],98:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&"json"in t}},{100:100}],99:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&r(t.paths)&&(o(t.jsonGraph)||o(t.jsong)||o(t.json)||o(t.values)||o(t.value))}},{100:100}],100:[function(t,e,n){var r="object";e.exports=function(t){return null!==t&&typeof t===r}},{}],101:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&(r(t.path)||"string"==typeof t.path)}},{100:100}],102:[function(t,e,n){var r="object";e.exports=function(t){return null==t||typeof t!==r}},{}],103:[function(t,e,n){var r=t(36),o=t(39),i=t(120),s=t(119),u=t(88),a=t(89),c=t(100),p=t(95),h=t(96),f=t(50),l=t(117),d=t(93),v=t(86),y=t(110),b=t(115),m=t(107);e.exports=function(t,e,n,g,w,x,_,S,E,C,A){var N,k,O,P,j,D,q;if(e===n){if(null===n)return e=l(n,void 0,n),t=b(t,-e.$size,E,_),e=d(e,t,g),f(E,e),e;if(void 0===n)return n;if(P=c(e),P&&(k=e.$type,null==k))return null==e[o]&&(e[r]=g,e[o]=t),e}else P=c(e),P&&(k=e.$type);if(k!==i){if(j=c(n),j&&(O=n.$type),P&&!k&&(null==n||j&&!O))return e}else{if(null==n)return p(e)?void v(e,S,E):e;if(j=c(n),j&&(O=n.$type,O===i))if(e===n){if(null!=e[o])return e}else if(D=e.$timestamp,q=n.$timestamp,!p(e)&&!p(n)&&D>q)return}if(k&&j&&!O)return d(y(e,n,t,g,E),t,g);if(O||!j){if(O===s&&h(A)&&(n=A(m(w,g),n)),O&&e===n)null==e[o]&&(e=l(e,k,e.value),t=b(t,-e.$size,E,_),e=d(e,t,g,_));else{var R=!0;!k&&P||(R=a(n)<a(e)==!1,(k||O)&&h(C)&&(R=!C(e,n,x.slice(0,x.index)))),R&&(n=l(n,O,O?n.value:n),N=u(e)-u(n),e=y(e,n,t,g,E),t=b(t,N,E,_),e=d(e,t,g,_))}p(e)?v(e,S,E):f(E,e)}else null==e&&(e=d(n,t,g));return e}},{100:100,107:107,110:110,115:115,117:117,119:119,120:120,36:36,39:39,50:50,86:86,88:88,89:89,93:93,95:95,96:96}],104:[function(t,e,n){var r=t(120),o=t(119),i=t(90),s=t(88),u=t(89),a=t(95),c=t(102),p=t(96),h=t(117),f=t(86),l=t(93),d=t(110),v=t(115),y=t(114),b=t(107);e.exports=function(t,e,n,m,g,w,x,_,S,E,C,A,N){var k=i(e,w);if(g||w)k&&a(e)&&(k="expired",f(e,E,C)),(k&&k!==r||c(e))&&(e=d(e,{},t,n,C),e=l(e,t,n,S),e=y(e,S));else{var O=m,P=i(O),j=u(O)<u(e)==!1;if((k||P)&&p(A)&&(j=!A(e,O,_.slice(0,_.index))),j){P===o&&p(N)&&(O=N(b(x,n),O)),O=h(O,P,P?O.value:O);var D=s(e)-s(O);e=d(e,O,t,n,C),t=v(t,D,C,S),e=l(e,t,n,S)}}return e}},{102:102,107:107,110:110,114:114,115:115,117:117,119:119,120:120,86:86,88:88,89:89,90:90,93:93,95:95,96:96}],105:[function(t,e,n){e.exports=function(){}},{}],106:[function(t,e,n){e.exports=Date.now},{}],107:[function(t,e,n){e.exports=function(t,e){var n=t.slice(0,t.depth);return n[n.length]=e,n}},{}],108:[function(t,e,n){var r=t(120),o=t(39),i=t(51),s=t(100),u=t(112),a=t(113);e.exports=function(t,e,n,c){if(s(t)){var p=t.$type;return Boolean(p)&&(p===r&&a(t),i(c,t)),u(t),e[n]=t[o]=void 0,!0}return!1}},{100:100,112:112,113:113,120:120,39:39,51:51}],109:[function(t,e,n){var r=t(91),o=t(40),i=t(108);e.exports=function s(t,e,n,u){if(i(t,e,n,u)){if(null==t.$type)for(var a in t)a[0]!==o&&"$"!==a[0]&&r(t,a)&&s(t[a],t,a,u);return!0}return!1}},{108:108,40:40,91:91}],110:[function(t,e,n){var r=t(100),o=t(111),i=t(109);e.exports=function(t,e,n,s,u){return t===e?t:(r(t)&&(o(t,e),i(t,n,s,u)),n[s]=e,e)}},{100:100,109:109,111:111}],111:[function(t,e,n){var r=t(43),o=t(33),i=t(44);e.exports=function(t,e){for(var n=t[i]||0,s=e[i]||0,u=-1;++u<n;){var a=t[r+u];void 0!==a&&(a[o]=e,e[r+(s+u)]=a,t[r+u]=void 0)}return e[i]=n+s,t[i]=void 0,e}},{33:33,43:43,44:44}],112:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){for(var e=-1,n=t[s]||0;++e<n;){var u=t[r+e];null!=u&&(u[o]=u[i]=t[r+e]=void 0)}return t[s]=void 0,t}},{33:33,42:42,43:43,44:44}],113:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){var e=t[o];if(e){for(var n=(t[i]||0)-1,u=(e[s]||0)-1;++n<=u;)e[r+n]=e[r+(n+1)];e[s]=u,t[i]=t[o]=e=void 0}return t}},{33:33,42:42,43:43,44:44}],114:[function(t,e,n){var r=t(43),o=t(39),i=t(46),s=t(44);e.exports=function(t,e){var n=[t],u=0;do{var a=n[u--];if(a&&a[i]!==e){a[i]=e,n[u++]=a[o];for(var c=-1,p=a[s]||0;++c<p;)n[u++]=a[r+c]}}while(u>-1);return t}},{39:39,43:43,44:44,46:46}],115:[function(t,e,n){var r=t(36),o=t(46),i=t(39),s=t(108),u=t(114);e.exports=function(t,e,n,a){var c=t;do{var p=c[i],h=c.$size=(c.$size||0)-e;0>=h&&null!=p?s(c,p,c[r],n):c[o]!==a&&u(c,a),c=p}while(c);return t}},{108:108,114:114,36:36,39:39,46:46}],116:[function(t,e,n){var r=Array.isArray,o=t(101),i=t(99),s=t(98),u=t(134);e.exports=function(t,e,n){for(var a=0,c=t.length;c>a;++a){var p=t[a],h=!1;if(r(p)&&e.path?h=!0:"string"==typeof p&&e.pathSyntax?h=!0:o(p)&&e.pathValue?(p.path=u.fromPath(p.path),h=!0):i(p)&&e.jsonGraph?h=!0:s(p)&&e.json?h=!0:"function"==typeof p&&a+1===c&&e.selector&&(h=!0),!h)return new Error("Unrecognized argument "+typeof p+" ["+String(p)+"] to Model#"+n)}return!0}},{101:101,134:134,98:98,99:99}],117:[function(t,e,n){var r=t(130),o=r.atom,i=t(106),s=t(122),u=t(37),a=50,c=t(85),p=Array.isArray,h=t(88),f=t(87);e.exports=function(t,e,n){var r=0,l=t,d=e;if(d?(l=c(l),r=h(l),l.$type=d):(l=o(n),d=l.$type,l[u]=!0),null==n)r=a+1;else if(null==r||0>=r)switch(typeof n){case"object":r=p(n)?a+n.length:a+1;break;case"string":r=a+n.length;break;default:r=a+1}var v=f(l);return"number"==typeof v&&s>v&&(l.$expires=i()+-1*v),l.$size=r,l}},{106:106,122:122,130:130,37:37,85:85,87:87,88:88}],118:[function(t,e,n){e.exports="atom"},{}],119:[function(t,e,n){e.exports="error"},{}],120:[function(t,e,n){e.exports="ref"},{}],121:[function(t,e,n){e.exports=1},{}],122:[function(t,e,n){e.exports=0},{}],123:[function(t,e,n){"use strict";function r(){if(a.length)throw a.shift()}function o(t){var e;e=u.length?u.pop():new i,e.task=t,s(e)}function i(){this.task=null}var s=t(124),u=[],a=[],c=s.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(t){o.onerror?o.onerror(t):(a.push(t),c())}finally{this.task=null,u[u.length]=this}}},{124:124}],124:[function(t,e,n){(function(t){"use strict";function n(t){u.length||(s(),a=!0),u[u.length]=t}function r(){for(;c<u.length;){var t=c;if(c+=1,u[t].call(),c>p){for(var e=0,n=u.length-c;n>e;e++)u[e]=u[e+c];u.length-=c,c=0}}u.length=0,c=0,a=!1}function o(t){var e=1,n=new h(t),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){e=-e,r.data=e}}function i(t){return function(){function e(){clearTimeout(n),clearInterval(r),t()}var n=setTimeout(e,0),r=setInterval(e,50)}}e.exports=n;var s,u=[],a=!1,c=0,p=1024,h=t.MutationObserver||t.WebKitMutationObserver;s="function"==typeof h?o(r):i(r),n.requestFlush=s,n.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],125:[function(t,e,n){"use strict";function r(t,e){var n;for(n in e)t[n]=e[n];return t}function o(t,e){if(this._jsongUrl=t,"number"==typeof e){var n={timeout:e};e=n}this._config=r({timeout:15e3,headers:{}},e||{})}var i=t(129),s=t(126);Array.isArray;o.prototype={constructor:o,buildQueryObject:s,get:function(t){var e="GET",n=this.buildQueryObject(this._jsongUrl,e,{paths:t,method:"get"}),o=r(n,this._config),s=this;return i(e,o,s)},set:function(t){var e="POST",n=this.buildQueryObject(this._jsongUrl,e,{jsonGraph:t,method:"set"}),o=r(n,this._config);o.headers["Content-Type"]="application/x-www-form-urlencoded";var s=this;return i(e,o,s)},call:function(t,e,n,o){e=e||[],n=n||[],o=o||[];var s="POST",u=[];u.push("method=call"),u.push("callPath="+encodeURIComponent(JSON.stringify(t))),u.push("arguments="+encodeURIComponent(JSON.stringify(e))),u.push("pathSuffixes="+encodeURIComponent(JSON.stringify(n))),u.push("paths="+encodeURIComponent(JSON.stringify(o)));var a=this.buildQueryObject(this._jsongUrl,s,u.join("&")),c=r(a,this._config);c.headers["Content-Type"]="application/x-www-form-urlencoded";var p=this;return i(s,c,p)}},o.XMLHttpSource=o,o["default"]=o,e.exports=o},{126:126,129:129}],126:[function(t,e,n){"use strict";e.exports=function(t,e,n){var r,o=[],i={url:t},s=-1!==t.indexOf("?"),u=s?"&":"?";return"string"==typeof n?o.push(n):(r=Object.keys(n),r.forEach(function(t){var e="object"==typeof n[t]?JSON.stringify(n[t]):n[t];o.push(t+"="+encodeURIComponent(e))})),"GET"===e?i.url+=u+o.join("&"):i.data=o.join("&"),i}},{}],127:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e=new t.XMLHttpRequest;if("withCredentials"in e)return e;if(t.XDomainRequest)return new XDomainRequest;throw new Error("CORS is not supported by your browser")}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],128:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e,n,r;if(t.XMLHttpRequest)return new t.XMLHttpRequest;try{for(n=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],r=0;3>r;r++)try{if(e=n[r],new t.ActiveXObject(e))break}catch(o){}return new t.ActiveXObject(e)}catch(o){throw new Error("XMLHttpRequest is not supported by your browser")}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],129:[function(t,e,n){"use strict";function r(){}function o(t,e,n){return r.create(function(r){var o,i,h,f,l,d={method:t||"GET",crossDomain:!1,async:!0,headers:{},responseType:"json"};for(l in e)p.call(e,l)&&(d[l]=e[l]);d.crossDomain||d.headers["X-Requested-With"]||(d.headers["X-Requested-With"]="XMLHttpRequest"),null!=n.onBeforeRequest&&n.onBeforeRequest(d);try{o=d.crossDomain?c():a()}catch(v){r.onError(v)}try{d.user?o.open(d.method,d.url,d.async,d.user,d.password):o.open(d.method,d.url,d.async),o.timeout=d.timeout,o.withCredentials=d.withCredentials!==!1,h=d.headers;for(f in h)p.call(h,f)&&o.setRequestHeader(f,h[f]);if(d.responseType)try{o.responseType=d.responseType}catch(y){if("json"!==d.responseType)throw y}o.onreadystatechange=function(t){4===o.readyState&&(i||(i=!0,s(r,o,t)))},o.ontimeout=function(t){i||(i=!0,u(r,o,"timeout error",t))},o.send(d.data)}catch(y){r.onError(y)}return function(){i||4===o.readyState||(i=!0,o.abort())}})}function i(t,e,n){n||(n=new Error(e)),t.onError(n)}function s(t,e,n){var r,o;if(e&&t){o=e.responseType,r="response"in e?e.response:e.responseText;var s=1223===e.status?204:e.status;if(s>=200&&399>=s){try{"json"!==o&&(r=JSON.parse(r||"")),"string"==typeof r&&(r=JSON.parse(r||""))}catch(n){i(t,"invalid json",n)}return t.onNext(r),void t.onCompleted()}return 401===s||403===s||407===s?i(t,r):410===s?i(t,r):408===s||504===s?i(t,r):i(t,r||"Response code "+s)}}function u(t,e,n,r){i(t,n||e.statusText||"request error",r)}var a=t(128),c=t(127),p=Object.prototype.hasOwnProperty,h=function(){};r.create=function(t){var e=new r;return e.subscribe=function(e,n,r){var o,i;return o="function"==typeof e?{onNext:e,onError:n||h,onCompleted:r||h}:e,i=t(o),"function"==typeof i?{dispose:i}:i},e},e.exports=o},{127:127,128:128}],130:[function(t,e,n){function r(t,e,n){var r=Object.create(null);if(null!=n){for(var o in n)r[o]=n[o];return r.$type=t,r.value=e,r}return{$type:t,value:e}}var o=t(134);e.exports={ref:function(t,e){return r("ref",o.fromPath(t),e)},atom:function(t,e){return r("atom",t,e)},undefined:function(){return r("atom")},error:function(t,e){return r("error",t,e)},pathValue:function(t,e){return{path:o.fromPath(t),value:e}},pathInvalidation:function(t){return{path:o.fromPath(t),invalidated:!0}}}},{134:134}],131:[function(t,e,n){e.exports={integers:"integers",ranges:"ranges",keys:"keys"}},{}],132:[function(t,e,n){var r={token:"token",dotSeparator:".",commaSeparator:",",openingBracket:"[",closingBracket:"]",openingBrace:"{",closingBrace:"}",escape:"\\",space:" ",colon:":",quote:"quote",unknown:"unknown"};e.exports=r},{}],133:[function(t,e,n){e.exports={indexer:{nested:"Indexers cannot be nested.",needQuotes:"unquoted indexers must be numeric.",empty:"cannot have empty indexers.",leadingDot:"Indexers cannot have leading dots.",leadingComma:"Indexers cannot have leading comma.",requiresComma:"Indexers require commas between indexer args.",routedTokens:"Only one token can be used per indexer when specifying routed tokens."},range:{precedingNaN:"ranges must be preceded by numbers.",suceedingNaN:"ranges must be suceeded by numbers."},routed:{invalid:"Invalid routed token.  only integers|ranges|keys are supported."},quote:{empty:"cannot have empty quoted keys.",illegalEscape:"Invalid escape character.  Only quotes are escapable."},unexpectedToken:"Unexpected token.",invalidIdentifier:"Invalid Identifier.",invalidPath:"Please provide a valid path.",throwError:function(t,e,n){if(n)throw t+" -- "+e.parseString+" with next token: "+n;throw t+" -- "+e.parseString}}},{}],134:[function(t,e,n){var r=t(140),o=t(135),i=t(131),s=function(t,e){return o(new r(t,e))};e.exports=s,s.fromPathsOrPathValues=function(t,e){if(!t)return[];for(var n=[],r=0,o=t.length;o>r;r++)"string"==typeof t[r]?n[r]=s(t[r],e):"string"==typeof t[r].path?n[r]={path:s(t[r].path,e),value:t[r].value}:n[r]=t[r];return n},s.fromPath=function(t,e){return t?"string"==typeof t?s(t,e):t:[]},s.RoutedTokens=i},{131:131,135:135,140:140}],135:[function(t,e,n){var r=t(132),o=t(133),i=t(136);e.exports=function(t){for(var e=t.next(),n={},s=[];!e.done;){switch(e.type){case r.token:var u=+e.token[0];isNaN(u)||o.throwError(o.invalidIdentifier,t),s[s.length]=e.token;break;case r.dotSeparator:0===s.length&&o.throwError(o.unexpectedToken,t);break;case r.space:break;case r.openingBracket:i(t,e,n,s);break;default:o.throwError(o.unexpectedToken,t)}e=t.next()}return 0===s.length&&o.throwError(o.invalidPath,t),s}},{132:132,133:133,136:136}],136:[function(t,e,n){var r=t(132),o=t(133),i=o.indexer,s=t(138),u=t(137),a=t(139);e.exports=function(t,e,n,c){var p=t.next(),h=!1,f=1,l=!1;for(n.indexer=[];!p.done;){switch(p.type){case r.token:case r.quote:n.indexer.length===f&&o.throwError(i.requiresComma,t)}switch(p.type){case r.openingBrace:l=!0,a(t,p,n,c);break;case r.token:var d=+p.token;isNaN(d)&&o.throwError(i.needQuotes,t),n.indexer[n.indexer.length]=d;break;case r.dotSeparator:n.indexer.length||o.throwError(i.leadingDot,t),s(t,p,n,c);
3457 break;case r.space:break;case r.closingBracket:h=!0;break;case r.quote:u(t,p,n,c);break;case r.openingBracket:o.throwError(i.nested,t);break;case r.commaSeparator:++f;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;p=t.next()}0===n.indexer.length&&o.throwError(i.empty,t),n.indexer.length>1&&l&&o.throwError(i.routedTokens,t),1===n.indexer.length&&(n.indexer=n.indexer[0]),c[c.length]=n.indexer,n.indexer=void 0}},{132:132,133:133,137:137,138:138,139:139}],137:[function(t,e,n){var r=t(132),o=t(133),i=o.quote;e.exports=function(t,e,n,s){for(var u=t.next(),a="",c=e.token,p=!1,h=!1;!u.done;){switch(u.type){case r.token:case r.space:case r.dotSeparator:case r.commaSeparator:case r.openingBracket:case r.closingBracket:case r.openingBrace:case r.closingBrace:p&&o.throwError(i.illegalEscape,t),a+=u.token;break;case r.quote:p?(a+=u.token,p=!1):u.token!==c?a+=u.token:h=!0;break;case r.escape:p=!0;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;u=t.next()}0===a.length&&o.throwError(i.empty,t),n.indexer[n.indexer.length]=a}},{132:132,133:133}],138:[function(t,e,n){var r=t(140),o=t(132),i=t(133);e.exports=function(t,e,n,s){var u,a=t.peek(),c=1,p=!1,h=!0,f=n.indexer.length-1,l=r.toNumber(n.indexer[f]);for(isNaN(l)&&i.throwError(i.range.precedingNaN,t);!p&&!a.done;){switch(a.type){case o.dotSeparator:3===c&&i.throwError(i.unexpectedToken,t),++c,3===c&&(h=!1);break;case o.token:u=r.toNumber(t.next().token),isNaN(u)&&i.throwError(i.range.suceedingNaN,t),p=!0;break;default:p=!0}if(p)break;t.next(),a=t.peek()}n.indexer[f]={from:l,to:h?u:u-1}}},{132:132,133:133,140:140}],139:[function(t,e,n){var r=t(132),o=t(131),i=t(133),s=i.routed;e.exports=function(t,e,n,u){var a=t.next(),c=!1,p="";switch(a.token){case o.integers:case o.ranges:case o.keys:break;default:i.throwError(s.invalid,t)}var h=t.next();if(h.type===r.colon&&(c=!0,h=t.next(),h.type!==r.token&&i.throwError(s.invalid,t),p=h.token,h=t.next()),h.type===r.closingBrace){var f={type:a.token,named:c,name:p};n.indexer[n.indexer.length]=f}else i.throwError(s.invalid,t)}},{131:131,132:132,133:133}],140:[function(t,e,n){function r(t,e,n){return{token:t,done:n,type:e}}function o(t,e,n){var o,g=!1,w="",x=n?m:b;do{if(o=e+1>=t.length)break;var _=t[e+1];if(void 0===_||-1!==x.indexOf(_)){if(w.length)break;++e;var S;switch(_){case s:S=i.dotSeparator;break;case u:S=i.commaSeparator;break;case a:S=i.openingBracket;break;case c:S=i.closingBracket;break;case p:S=i.openingBrace;break;case h:S=i.closingBrace;break;case y:S=i.space;break;case d:case v:S=i.quote;break;case l:S=i.escape;break;case f:S=i.colon;break;default:S=i.unknown}g=r(_,S,!1);break}w+=_,++e}while(!o);return!g&&w.length&&(g=r(w,i.token,!1)),g||(g={done:!0}),{token:g,idx:e}}var i=t(132),s=".",u=",",a="[",c="]",p="{",h="}",f=":",l="\\",d='"',v="'",y=" ",b="\\'\"[]., ",m="\\{}'\"[]., :",g=e.exports=function(t,e){this._string=t,this._idx=-1,this._extended=e,this.parseString=""};g.prototype={next:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._idx=t.idx,this._nextToken=!1,this.parseString+=t.token.token,t.token},peek:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._nextToken=t,t.token}},g.toNumber=function(t){return isNaN(+t)?NaN:+t}},{132:132}],141:[function(t,e,n){var r=t(147),o=t(148);e.exports=function(t){var e=t.reduce(function(t,e){var n=e.length;return t[n]||(t[n]=[]),t[n].push(e),t},{});return Object.keys(e).forEach(function(t){e[t]=o(e[t])}),r(e)}},{147:147,148:148}],142:[function(t,e,n){var r=t(144);e.exports=function o(t,e,n){for(var i=t,s=!0;s&&n<e.length;++n){var u=e[n],a=typeof u;if(u&&"object"===a){var c={},p=r(u,c),h=n+1;do{var f=i[p];s=void 0!==f,s&&(s=o(f,e,h)),p=r(u,c)}while(s&&!c.done);break}i=i[u],s=void 0!==i}return s}},{144:144}],143:[function(t,e,n){e.exports={iterateKeySet:t(144),toTree:t(148),toTreeWithUnion:t(149),pathsComplementFromTree:t(146),pathsComplementFromLengthTree:t(145),hasIntersection:t(142),toPaths:t(147),collapse:t(141)}},{141:141,142:142,144:144,145:145,146:146,147:147,148:148,149:149}],144:[function(t,e,n){function r(t,e){var n=e.from=t.from||0,r=e.to=t.to||"number"==typeof t.length&&e.from+t.length-1||0;e.rangeOffset=e.from,e.loaded=!0,n>r&&(e.empty=!0)}function o(t,e){e.done=!1;var n=e.isObject=!(!t||"object"!=typeof t);e.isArray=n&&i(t),e.arrayOffset=0}var i=Array.isArray;e.exports=function(t,e){if(void 0===e.isArray&&o(t,e),e.isArray){var n;do{e.loaded&&e.rangeOffset>e.to&&(++e.arrayOffset,e.loaded=!1);var i=e.arrayOffset,s=t.length;if(i>=s){e.done=!0;break}var u=t[e.arrayOffset],a=typeof u;if("object"===a){if(e.loaded||r(u,e),e.empty)continue;n=e.rangeOffset++}else++e.arrayOffset,n=u}while(void 0===n);return n}return e.isObject?(e.loaded||r(t,e),e.rangeOffset>e.to?void(e.done=!0):e.rangeOffset++):(e.done=!0,t)}},{}],145:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i){var u=t[i];r(e[u.length],u,0)||(n[++o]=u)}return n}},{142:142}],146:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i)r(e,t[i],0)||(n[++o]=t[i]);return n}},{142:142}],147:[function(t,e,n){function r(t){return null!==t&&typeof t===f}function o(t,e,n){var r,i,s,u,h,f,l,d,v,y,b,m,g,w,x=c(String(e)),_=Object.create(null),S=[],E=-1,C=0,A=[],N=0;if(u=[],h=-1,n-1>e){for(f=a(t,u);++h<f;)r=u[h],i=o(t[r],e+1,n),s=i.code,_[s]?i=_[s]:(S[C++]=s,i=_[s]={keys:[],sets:i.sets}),x=c(x+r+s),p(r)&&i.keys.push(parseInt(r,10))||i.keys.push(r);for(;++E<C;)if(r=S[E],i=_[r],u=i.keys,f=u.length,f>0)for(l=i.sets,d=-1,v=l.length,g=u[0];++d<v;){for(y=l[d],b=-1,m=y.length,w=new Array(m+1),w[0]=f>1&&u||g;++b<m;)w[b+1]=y[b];A[N++]=w}}else for(f=a(t,u),f>1?A[N++]=[u]:A[N++]=u;++h<f;)x=c(x+u[h]);return{code:x,sets:A}}function i(t){for(var e=-1,n=t.length;++e<n;){var r=t[e];h(r)&&(t[e]=s(r))}return t}function s(t){for(var e=-1,n=t.length-1,r=n>0;++e<=n;){var o=t[e];if(!p(o)){r=!1;break}t[e]=parseInt(o,10)}if(r===!0){t.sort(u);var i=t[0],s=t[n];if(n>=s-i)return{from:i,to:s}}return t}function u(t,e){return t-e}function a(t,e,n){var r=0;for(var o in t)e[r++]=o;return r>1&&e.sort(n),r}function c(t){for(var e=5381,n=-1,r=t.length;++n<r;)e=(e<<5)+e+t.charCodeAt(n);return String(e)}function p(t){return!h(t)&&t-parseFloat(t)+1>=0}var h=Array.isArray,f="object";e.exports=function(t){var e,n=[],s=0;for(var u in t)if(p(u)&&r(e=t[u]))for(var a=o(e,0,parseInt(u,10)).sets,c=-1,h=a.length;++c<h;)n[s++]=i(a[c]);return n}},{}],148:[function(t,e,n){function r(t,e,n){var i,s=e[n],u={},a=n+1;i=o(s,u);do{var c=t[i];c||(a===e.length?t[i]=null:c=t[i]={}),a<e.length&&r(c,e,a),u.done||(i=o(s,u))}while(!u.done)}var o=t(144);Array.isArray;e.exports=function(t){return t.reduce(function(t,e){return r(t,e,0),t},{})}},{144:144}],149:[function(t,e,n){},{}],150:[function(t,e,n){function r(){p=!1,u.length?c=u.concat(c):h=-1,c.length&&o()}function o(){if(!p){var t=setTimeout(r);p=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,p=!1,clearTimeout(t)}}function i(t,e){this.fun=t,this.array=e}function s(){}var u,a=e.exports={},c=[],p=!1,h=-1;a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new i(t,e)),1!==c.length||p||setTimeout(o,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=s,a.addListener=s,a.once=s,a.off=s,a.removeListener=s,a.removeAllListeners=s,a.emit=s,a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],151:[function(t,e,n){"use strict";e.exports=t(156)},{156:156}],152:[function(t,e,n){"use strict";function r(){}function o(t){try{return t.then}catch(e){return y=e,b}}function i(t,e){try{return t(e)}catch(n){return y=n,b}}function s(t,e,n){try{t(e,n)}catch(r){return y=r,b}}function u(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],t!==r&&d(t,this)}function a(t,e,n){return new t.constructor(function(o,i){var s=new u(r);s.then(o,i),c(t,new l(e,n,s))})}function c(t,e){for(;3===t._37;)t=t._12;return 0===t._37?void t._59.push(e):void v(function(){var n=1===t._37?e.onFulfilled:e.onRejected;if(null===n)return void(1===t._37?p(e.promise,t._12):h(e.promise,t._12));var r=i(n,t._12);r===b?h(e.promise,y):p(e.promise,r)})}function p(t,e){if(e===t)return h(t,new TypeError("A promise cannot be resolved with itself."));if(e&&("object"==typeof e||"function"==typeof e)){var n=o(e);if(n===b)return h(t,y);if(n===t.then&&e instanceof u)return t._37=3,t._12=e,void f(t);if("function"==typeof n)return void d(n.bind(e),t)}t._37=1,t._12=e,f(t)}function h(t,e){t._37=2,t._12=e,f(t)}function f(t){for(var e=0;e<t._59.length;e++)c(t,t._59[e]);t._59=null}function l(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function d(t,e){var n=!1,r=s(t,function(t){n||(n=!0,p(e,t))},function(t){n||(n=!0,h(e,t))});n||r!==b||(n=!0,h(e,y))}var v=t(124),y=null,b={};e.exports=u,u._99=r,u.prototype.then=function(t,e){if(this.constructor!==u)return a(this,t,e);var n=new u(r);return c(this,new l(t,e,n)),n}},{124:124}],153:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype.done=function(t,e){var n=arguments.length?this.then.apply(this,arguments):this;n.then(null,function(t){setTimeout(function(){throw t},0)})}},{152:152}],154:[function(t,e,n){"use strict";function r(t){var e=new o(o._99);return e._37=1,e._12=t,e}var o=t(152);e.exports=o;var i=r(!0),s=r(!1),u=r(null),a=r(void 0),c=r(0),p=r("");o.resolve=function(t){if(t instanceof o)return t;if(null===t)return u;if(void 0===t)return a;if(t===!0)return i;if(t===!1)return s;if(0===t)return c;if(""===t)return p;if("object"==typeof t||"function"==typeof t)try{var e=t.then;if("function"==typeof e)return new o(e.bind(t))}catch(n){return new o(function(t,e){e(n)})}return r(t)},o.all=function(t){var e=Array.prototype.slice.call(t);return new o(function(t,n){function r(s,u){if(u&&("object"==typeof u||"function"==typeof u)){if(u instanceof o&&u.then===o.prototype.then){for(;3===u._37;)u=u._12;return 1===u._37?r(s,u._12):(2===u._37&&n(u._12),void u.then(function(t){r(s,t)},n))}var a=u.then;if("function"==typeof a){var c=new o(a.bind(u));return void c.then(function(t){r(s,t)},n)}}e[s]=u,0===--i&&t(e)}if(0===e.length)return t([]);for(var i=e.length,s=0;s<e.length;s++)r(s,e[s])})},o.reject=function(t){return new o(function(e,n){n(t)})},o.race=function(t){return new o(function(e,n){t.forEach(function(t){o.resolve(t).then(e,n)})})},o.prototype["catch"]=function(t){return this.then(null,t)}},{152:152}],155:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype["finally"]=function(t){return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){throw e})})}},{152:152}],156:[function(t,e,n){"use strict";e.exports=t(152),t(153),t(155),t(154),t(157)},{152:152,153:153,154:154,155:155,157:157}],157:[function(t,e,n){"use strict";var r=t(152),o=t(123);e.exports=r,r.denodeify=function(t,e){return e=e||1/0,function(){var n=this,o=Array.prototype.slice.call(arguments,0,e>0?e:0);return new r(function(e,r){o.push(function(t,n){t?r(t):e(n)});var i=t.apply(n,o);!i||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then||e(i)})}},r.nodeify=function(t){return function(){var e=Array.prototype.slice.call(arguments),n="function"==typeof e[e.length-1]?e.pop():null,i=this;try{return t.apply(this,arguments).nodeify(n,i)}catch(s){if(null===n||"undefined"==typeof n)return new r(function(t,e){e(s)});o(function(){n.call(i,s)})}}},r.prototype.nodeify=function(t,e){return"function"!=typeof t?this:void this.then(function(n){o(function(){t.call(e,null,n)})},function(n){o(function(){t.call(e,n)})})}},{123:123,152:152}],158:[function(e,n,r){(function(o){(function(i){var s={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},u=s[typeof window]&&window||this,a=s[typeof r]&&r&&!r.nodeType&&r,c=s[typeof n]&&n&&!n.nodeType&&n,p=(c&&c.exports===a&&a,s[typeof o]&&o);!p||p.global!==p&&p.window!==p||(u=p),"function"==typeof t&&t.amd?t(["rx"],function(t,e){return i(u,e,t)}):"object"==typeof n&&n&&n.exports===a?n.exports=i(u,n.exports,e(159)):u.Rx=i(u,{},u.Rx)}).call(this,function(t,e,n,r){function o(){try{return l.apply(this,arguments)}catch(t){return M.e=t,M}}function i(t){if(!E(t))throw new TypeError("fn must be a function");return l=t,o}function s(t,e,n){return new b(function(r){var o=!1,i=null,s=[];return t.subscribe(function(t){var u,a;try{a=e(t)}catch(c){return void r.onError(c)}if(u=0,o)try{u=n(a,i)}catch(p){return void r.onError(p)}else o=!0,i=a;u>0&&(i=a,s=[]),u>=0&&s.push(t)},function(t){r.onError(t)},function(){r.onNext(s),r.onCompleted()})},t)}function u(t){if(0===t.length)throw new D;return t[0]}function a(t,e,n,r){if(0>e)throw new R;return new b(function(o){var i=e;return t.subscribe(function(t){0===i--&&(o.onNext(t),o.onCompleted())},function(t){o.onError(t)},function(){n?(o.onNext(r),o.onCompleted()):o.onError(new R)})},t)}function c(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){i?r.onError(new Error("Sequence contains more than one element")):(o=t,i=!0)},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function p(t,e,n){return new b(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},function(t){r.onError(t)},function(){e?(r.onNext(n),r.onCompleted()):r.onError(new D)})},t)}function h(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){o=t,i=!0},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function f(t,e,n,o){var i=j(e,n,3);return new b(function(e){var n=0;return t.subscribe(function(r){var s;try{s=i(r,n,t)}catch(u){return void e.onError(u)}s?(e.onNext(o?n:r),e.onCompleted()):n++},function(t){e.onError(t)},function(){e.onNext(o?-1:r),e.onCompleted()})},t)}var l,d=n.Observable,v=d.prototype,y=n.CompositeDisposable,b=n.AnonymousObservable,m=n.Disposable.empty,g=(n.internals.isEqual,n.helpers),w=g.not,x=g.defaultComparer,_=g.identity,S=g.defaultSubComparer,E=g.isFunction,C=g.isPromise,A=g.isArrayLike,N=g.isIterable,k=n.internals.inherits,O=d.fromPromise,P=d.from,j=n.internals.bindCallback,D=n.EmptyError,q=n.ObservableBase,R=n.ArgumentOutOfRangeError,M={e:{}};v.aggregate=function(){var t,e,n=!1,r=this;return 2===arguments.length?(n=!0,e=arguments[0],t=arguments[1]):t=arguments[0],new b(function(o){var i,s,u;return r.subscribe(function(r){!u&&(u=!0);try{i?s=t(s,r):(s=n?t(e,r):r,i=!0)}catch(a){return o.onError(a)}},function(t){o.onError(t)},function(){u&&o.onNext(s),!u&&n&&o.onNext(e),!u&&!n&&o.onError(new D),o.onCompleted()})},r)};var T=function(t){function e(e,n,r,o){this.source=e,this.acc=n,this.hasSeed=r,this.seed=o,t.call(this)}function n(t,e){this.o=t,this.acc=e.acc,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.result=null,this.hasValue=!1,this.isStopped=!1}return k(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this))},n.prototype.onNext=function(t){this.isStopped||(!this.hasValue&&(this.hasValue=!0),this.hasAccumulation?this.result=i(this.acc)(this.result,t):(this.result=this.hasSeed?i(this.acc)(this.seed,t):t,this.hasAccumulation=!0),this.result===M&&this.o.onError(this.result.e))},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.hasValue&&this.o.onNext(this.result),!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed),!this.hasValue&&!this.hasSeed&&this.o.onError(new D),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(q);return v.reduce=function(t){var e=!1;if(2===arguments.length){e=!0;var n=arguments[1]}return new T(this,t,e,n)},v.some=function(t,e){var n=this;return t?n.filter(t,e).some():new b(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},function(e){t.onError(e)},function(){t.onNext(!1),t.onCompleted()})},n)},v.any=function(){return this.some.apply(this,arguments)},v.isEmpty=function(){return this.any().map(w)},v.every=function(t,e){return this.filter(function(e){return!t(e)},e).some().map(w)},v.all=function(){return this.every.apply(this,arguments)},v.includes=function(t,e){function n(t,e){return 0===t&&0===e||t===e||isNaN(t)&&isNaN(e)}var r=this;return new b(function(o){var i=0,s=+e||0;return Math.abs(s)===1/0&&(s=0),0>s?(o.onNext(!1),o.onCompleted(),m):r.subscribe(function(e){i++>=s&&n(e,t)&&(o.onNext(!0),o.onCompleted())},function(t){o.onError(t)},function(){o.onNext(!1),o.onCompleted()})},this)},v.contains=function(t,e){v.includes(t,e)},v.count=function(t,e){return t?this.filter(t,e).count():this.reduce(function(t){return t+1},0)},v.indexOf=function(t,e){var n=this;return new b(function(r){var o=0,i=+e||0;return Math.abs(i)===1/0&&(i=0),0>i?(r.onNext(-1),r.onCompleted(),m):n.subscribe(function(e){o>=i&&e===t&&(r.onNext(o),r.onCompleted()),o++},function(t){r.onError(t)},function(){r.onNext(-1),r.onCompleted()})},n)},v.sum=function(t,e){return t&&E(t)?this.map(t,e).sum():this.reduce(function(t,e){return t+e},0)},v.minBy=function(t,e){return e||(e=S),s(this,t,function(t,n){return-1*e(t,n)})},v.min=function(t){return this.minBy(_,t).map(function(t){return u(t)})},v.maxBy=function(t,e){return e||(e=S),s(this,t,e)},v.max=function(t){return this.maxBy(_,t).map(function(t){return u(t)})},v.average=function(t,e){return t&&E(t)?this.map(t,e).average():this.reduce(function(t,e){return{sum:t.sum+e,count:t.count+1}},{sum:0,count:0}).map(function(t){if(0===t.count)throw new D;return t.sum/t.count})},v.sequenceEqual=function(t,e){var n=this;return e||(e=x),new b(function(r){var o=!1,i=!1,s=[],u=[],a=n.subscribe(function(t){var n,o;if(u.length>0){o=u.shift();try{n=e(o,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else i?(r.onNext(!1),r.onCompleted()):s.push(t)},function(t){r.onError(t)},function(){o=!0,0===s.length&&(u.length>0?(r.onNext(!1),r.onCompleted()):i&&(r.onNext(!0),r.onCompleted()))});(A(t)||N(t))&&(t=P(t)),C(t)&&(t=O(t));var c=t.subscribe(function(t){var n;if(s.length>0){var i=s.shift();try{n=e(i,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else o?(r.onNext(!1),r.onCompleted()):u.push(t)},function(t){r.onError(t)},function(){i=!0,0===u.length&&(s.length>0?(r.onNext(!1),r.onCompleted()):o&&(r.onNext(!0),r.onCompleted()))});return new y(a,c)},n)},v.elementAt=function(t){return a(this,t,!1)},v.elementAtOrDefault=function(t,e){return a(this,t,!0,e)},v.single=function(t,e){return t&&E(t)?this.where(t,e).single():c(this,!1)},v.singleOrDefault=function(t,e,n){return t&&E(t)?this.filter(t,n).singleOrDefault(null,e):c(this,!0,e)},v.first=function(t,e){return t?this.where(t,e).first():p(this,!1)},v.firstOrDefault=function(t,e,n){return t?this.where(t).firstOrDefault(null,e):p(this,!0,e)},v.last=function(t,e){return t?this.where(t,e).last():h(this,!1)},v.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):h(this,!0,e)},v.find=function(t,e){return f(this,t,e,!1)},v.findIndex=function(t,e){return f(this,t,e,!0)},v.toSet=function(){if("undefined"==typeof t.Set)throw new TypeError;var e=this;return new b(function(n){var r=new t.Set;return e.subscribe(function(t){r.add(t)},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},v.toMap=function(e,n){if("undefined"==typeof t.Map)throw new TypeError;var r=this;return new b(function(o){var i=new t.Map;return r.subscribe(function(t){var r;try{r=e(t)}catch(s){return void o.onError(s)}var u=t;if(n)try{u=n(t)}catch(s){return void o.onError(s)}i.set(r,u)},function(t){o.onError(t)},function(){o.onNext(i),o.onCompleted()})},r)},n})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{159:159}],159:[function(e,n,r){(function(e,o){(function(i){function u(t){for(var e=[],n=0,r=t.length;r>n;n++)e.push(t[n]);return e}function a(t,e){if(ct&&e.stack&&"object"==typeof t&&null!==t&&t.stack&&-1===t.stack.indexOf(lt)){for(var n=[],r=e;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(t.stack);var o=n.join("\n"+lt+"\n");t.stack=c(o)}}function c(t){for(var e=t.split("\n"),n=[],r=0,o=e.length;o>r;r++){var i=e[r];p(i)||h(i)||!i||n.push(i)}return n.join("\n")}function p(t){var e=l(t);if(!e)return!1;var n=e[0],r=e[1];return n===ht&&r>=ft&&$n>=r}function h(t){return-1!==t.indexOf("(module.js:")||-1!==t.indexOf("(node.js:")}function f(){if(ct)try{throw new Error}catch(t){var e=t.stack.split("\n"),n=e[0].indexOf("@")>0?e[1]:e[2],r=l(n);if(!r)return;return ht=r[0],r[1]}}function l(t){var e=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(t);if(e)return[e[1],Number(e[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(t);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(t);return r?[r[1],Number(r[2])]:void 0}function d(t){var e=[];if(!Ht(t))return e;Ut.nonEnumArgs&&t.length&&Xt(t)&&(t=Yt.call(t));var n=Ut.enumPrototypes&&"function"==typeof t,r=Ut.enumErrorProps&&(t===Jt||t instanceof Error);for(var o in t)n&&"prototype"==o||r&&("message"==o||"name"==o)||e.push(o);if(Ut.nonEnumShadows&&t!==It){var i=t.constructor,s=-1,u=kt;if(t===(i&&i.prototype))var a=t===Lt?$t:t===Jt?qt:Wt.call(t),c=Ft[a];for(;++s<u;)o=Nt[s],c&&c[o]||!zt.call(t,o)||e.push(o)}return e}function v(t,e,n){for(var r=-1,o=n(t),i=o.length;++r<i;){var s=o[r];if(e(t[s],s,t)===!1)break}return t}function y(t,e){return v(t,e,d)}function b(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function m(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;var o=typeof t,i=typeof e;if(t===t&&(null==t||null==e||"function"!=o&&"object"!=o&&"function"!=i&&"object"!=i))return!1;var s=Wt.call(t),u=Wt.call(e);if(s==Ot&&(s=Tt),u==Ot&&(u=Tt),s!=u)return!1;switch(s){case jt:case Dt:return+t==+e;case Mt:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case Vt:case $t:return t==String(e)}var a=s==Pt;if(!a){if(s!=Tt||!Ut.nodeClass&&(b(t)||b(e)))return!1;var c=!Ut.argsObject&&Xt(t)?Object:t.constructor,p=!Ut.argsObject&&Xt(e)?Object:e.constructor;if(!(c==p||zt.call(t,"constructor")&&zt.call(e,"constructor")||at(c)&&c instanceof c&&at(p)&&p instanceof p||!("constructor"in t&&"constructor"in e)))return!1}n||(n=[]),r||(r=[]);for(var h=n.length;h--;)if(n[h]==t)return r[h]==e;var f=0,l=!0;if(n.push(t),r.push(e),a){if(h=t.length,f=e.length,l=f==h)for(;f--;){var d=e[f];if(!(l=m(t[f],d,n,r)))break}}else y(e,function(e,o,i){return zt.call(i,o)?(f++,l=zt.call(t,o)&&m(t[o],e,n,r)):void 0}),l&&y(t,function(t,e,n){return zt.call(n,e)?l=--f>-1:void 0});return n.pop(),r.pop(),l}function g(t,e){for(var n=new Array(t),r=0;t>r;r++)n[r]=e();return n}function w(){try{return Qt.apply(this,arguments)}catch(t){return ne.e=t,ne}}function x(t){if(!at(t))throw new TypeError("fn must be a function");return Qt=t,w}function _(t){throw t}function S(t,e){this.id=t,this.value=e}function E(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function C(t,e){e.isDisposed||(e.isDisposed=!0,e.disposable.dispose())}function A(t){this._s=s}function N(t){this._s=s,this._l=s.length,this._i=0}function k(t){this._a=t}function O(t){this._a=t,this._l=q(t),this._i=0}function P(t){return"number"==typeof t&&X.isFinite(t)}function j(t){var e,n=t[xt];if(!n&&"string"==typeof t)return e=new A(t),e[xt]();if(!n&&t.length!==i)return e=new k(t),e[xt]();if(!n)throw new TypeError("Object is not iterable");return t[xt]()}function D(t){var e=+t;return 0===e?e:isNaN(e)?e:0>e?-1:1}function q(t){var e=+t.length;return isNaN(e)?0:0!==e&&P(e)?(e=D(e)*Math.floor(Math.abs(e)),0>=e?0:e>en?en:e):e}function R(t,e){this.observer=t,this.parent=e}function M(t,e){return me(t)||(t=_e),new rn(e,t)}function T(t,e){this.observer=t,this.parent=e}function V(t,e){this.observer=t,this.parent=e}function $(t,e){return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.subscribe(function(t){n.onNext(t)},function(t){try{var r=e(t)}catch(i){return n.onError(i)}ut(r)&&(r=Xe(r));var s=new fe;o.setDisposable(s),s.setDisposable(r.subscribe(n))},function(t){n.onCompleted(t)})),o},t)}function W(){return!1}function z(t,e){var n=this;return new qn(function(r){var o=0,i=t.length;return n.subscribe(function(n){if(i>o){var s=t[o++],u=x(e)(n,s);if(u===ne)return r.onError(u.e);r.onNext(u)}else r.onCompleted()},function(t){r.onError(t)},function(){r.onCompleted()})},n)}function W(){return!1}function G(){return[]}function W(){return!1}function J(){return[]}function I(t,e){this.observer=t,this.accumulator=e.accumulator,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.accumulation=null,this.hasValue=!1,this.isStopped=!1}function L(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).concatAll()}function B(t,e,n){for(var r=0,o=t.length;o>r;r++)if(n(t[r],e))return r;return-1}function F(t){this.comparer=t,this.set=[]}function U(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).mergeAll()}var H={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X=H[typeof window]&&window||this,Q=H[typeof r]&&r&&!r.nodeType&&r,K=H[typeof n]&&n&&!n.nodeType&&n,Y=K&&K.exports===Q&&Q,Z=H[typeof o]&&o;!Z||Z.global!==Z&&Z.window!==Z||(X=Z);var tt={internals:{},config:{Promise:X.Promise},helpers:{}},et=tt.helpers.noop=function(){},nt=(tt.helpers.notDefined=function(t){return"undefined"==typeof t},tt.helpers.identity=function(t){return t}),rt=(tt.helpers.pluck=function(t){return function(e){return e[t]}},tt.helpers.just=function(t){return function(){return t}},tt.helpers.defaultNow=Date.now),ot=tt.helpers.defaultComparer=function(t,e){return Kt(t,e)},it=tt.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},st=(tt.helpers.defaultKeySerializer=function(t){return t.toString()},tt.helpers.defaultError=function(t){throw t}),ut=tt.helpers.isPromise=function(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then},at=(tt.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},tt.helpers.not=function(t){return!t},tt.helpers.isFunction=function(){var t=function(t){return"function"==typeof t||!1};return t(/x/)&&(t=function(t){return"function"==typeof t&&"[object Function]"==Wt.call(t)}),t}());tt.config.longStackSupport=!1;var ct=!1;try{throw new Error}catch(pt){ct=!!pt.stack}var ht,ft=f(),lt="From previous event:",dt=tt.EmptyError=function(){this.message="Sequence contains no elements.",Error.call(this)};dt.prototype=Error.prototype;var vt=tt.ObjectDisposedError=function(){this.message="Object has been disposed",Error.call(this)};vt.prototype=Error.prototype;var yt=tt.ArgumentOutOfRangeError=function(){this.message="Argument out of range",Error.call(this)};yt.prototype=Error.prototype;var bt=tt.NotSupportedError=function(t){this.message=t||"This operation is not supported",Error.call(this)};bt.prototype=Error.prototype;var mt=tt.NotImplementedError=function(t){this.message=t||"This operation is not implemented",Error.call(this)};mt.prototype=Error.prototype;var gt=tt.helpers.notImplemented=function(){throw new mt},wt=tt.helpers.notSupported=function(){throw new bt},xt="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";X.Set&&"function"==typeof(new X.Set)["@@iterator"]&&(xt="@@iterator");var _t=tt.doneEnumerator={done:!0,value:i},St=tt.helpers.isIterable=function(t){return t[xt]!==i},Et=tt.helpers.isArrayLike=function(t){return t&&t.length!==i};tt.helpers.iterator=xt;var Ct,At=tt.internals.bindCallback=function(t,e,n){if("undefined"==typeof e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}},Nt=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],kt=Nt.length,Ot="[object Arguments]",Pt="[object Array]",jt="[object Boolean]",Dt="[object Date]",qt="[object Error]",Rt="[object Function]",Mt="[object Number]",Tt="[object Object]",Vt="[object RegExp]",$t="[object String]",Wt=Object.prototype.toString,zt=Object.prototype.hasOwnProperty,Gt=Wt.call(arguments)==Ot,Jt=Error.prototype,It=Object.prototype,Lt=String.prototype,Bt=It.propertyIsEnumerable;try{Ct=!(Wt.call(document)==Tt&&!({toString:0}+""))}catch(pt){Ct=!0}var Ft={};Ft[Pt]=Ft[Dt]=Ft[Mt]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Ft[jt]=Ft[$t]={constructor:!0,toString:!0,valueOf:!0},Ft[qt]=Ft[Rt]=Ft[Vt]={constructor:!0,toString:!0},Ft[Tt]={constructor:!0};var Ut={};!function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);Ut.enumErrorProps=Bt.call(Jt,"message")||Bt.call(Jt,"name"),Ut.enumPrototypes=Bt.call(t,"prototype"),Ut.nonEnumArgs=0!=n,Ut.nonEnumShadows=!/valueOf/.test(e)}(1);var Ht=tt.internals.isObject=function(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1},Xt=function(t){return t&&"object"==typeof t?Wt.call(t)==Ot:!1};Gt||(Xt=function(t){return t&&"object"==typeof t?zt.call(t,"callee"):!1});var Qt,Kt=tt.internals.isEqual=function(t,e){return m(t,e,[],[])},Yt=({}.hasOwnProperty,Array.prototype.slice),Zt=this.inherits=tt.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},te=tt.internals.addProperties=function(t){for(var e=[],n=1,r=arguments.length;r>n;n++)e.push(arguments[n]);for(var o=0,i=e.length;i>o;o++){var s=e[o];for(var u in s)t[u]=s[u]}},ee=tt.internals.addRef=function(t,e){return new qn(function(n){return new ie(e.getDisposable(),t.subscribe(n))})},ne={e:{}};S.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var re=tt.internals.PriorityQueue=function(t){this.items=new Array(t),this.length=0},oe=re.prototype;oe.isHigherPriority=function(t,e){return this.items[t].compareTo(this.items[e])<0},oe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},oe.heapify=function(t){if(+t||(t=0),!(t>=this.length||0>t)){var e=2*t+1,n=2*t+2,r=t;if(e<this.length&&this.isHigherPriority(e,r)&&(r=e),n<this.length&&this.isHigherPriority(n,r)&&(r=n),r!==t){var o=this.items[t];this.items[t]=this.items[r],this.items[r]=o,this.heapify(r)}}},oe.peek=function(){return this.items[0].value},oe.removeAt=function(t){this.items[t]=this.items[--this.length],this.items[this.length]=i,this.heapify()},oe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},oe.enqueue=function(t){var e=this.length++;this.items[e]=new S(re.count++,t),this.percolate(e)},oe.remove=function(t){for(var e=0;e<this.length;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},re.count=0;var ie=tt.CompositeDisposable=function(){var t,e,n=[];if(Array.isArray(arguments[0]))n=arguments[0],e=n.length;else for(e=arguments.length,n=new Array(e),t=0;e>t;t++)n[t]=arguments[t];for(t=0;e>t;t++)if(!pe(n[t]))throw new TypeError("Not a disposable");this.disposables=n,this.isDisposed=!1,this.length=n.length},se=ie.prototype;se.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},se.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},se.dispose=function(){
3458 if(!this.isDisposed){this.isDisposed=!0;for(var t=this.disposables.length,e=new Array(t),n=0;t>n;n++)e[n]=this.disposables[n];for(this.disposables=[],this.length=0,n=0;t>n;n++)e[n].dispose()}};var ue=tt.Disposable=function(t){this.isDisposed=!1,this.action=t||et};ue.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ae=ue.create=function(t){return new ue(t)},ce=ue.empty={dispose:et},pe=ue.isDisposable=function(t){return t&&at(t.dispose)},he=ue.checkDisposed=function(t){if(t.isDisposed)throw new vt},fe=tt.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null};fe.prototype.getDisposable=function(){return this.current},fe.prototype.setDisposable=function(t){if(this.current)throw new Error("Disposable has already been assigned");var e=this.isDisposed;!e&&(this.current=t),e&&t&&t.dispose()},fe.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var le=tt.SerialDisposable=function(){this.isDisposed=!1,this.current=null};le.prototype.getDisposable=function(){return this.current},le.prototype.setDisposable=function(t){var e=this.isDisposed;if(!e){var n=this.current;this.current=t}n&&n.dispose(),e&&t&&t.dispose()},le.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var de=tt.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ce:new t(this)},e}();E.prototype.dispose=function(){this.scheduler.scheduleWithState(this,C)};var ve=tt.internals.ScheduledItem=function(t,e,n,r,o){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=o||it,this.disposable=new fe};ve.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ve.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ve.prototype.isCancelled=function(){return this.disposable.isDisposed},ve.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ye=tt.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){return e(),ce}t.isScheduler=function(e){return e instanceof t};var n=t.prototype;return n.schedule=function(t){return this._schedule(t,e)},n.scheduleWithState=function(t,e){return this._schedule(t,e)},n.scheduleWithRelative=function(t,n){return this._scheduleRelative(n,t,e)},n.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},n.scheduleWithAbsolute=function(t,n){return this._scheduleAbsolute(n,t,e)},n.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},t.now=rt,t.normalize=function(t){return 0>t&&(t=0),t},t}(),be=ye.normalize,me=ye.isScheduler;!function(t){function e(t,e){function n(e){o(e,function(e){var r=!1,o=!1,s=t.scheduleWithState(e,function(t,e){return r?i.remove(s):o=!0,n(e),ce});o||(i.add(s),r=!0)})}var r=e[0],o=e[1],i=new ie;return n(r),i}function n(t,e,n){function r(e){i(e,function(e,o){var i=!1,u=!1,a=t[n](e,o,function(t,e){return i?s.remove(a):u=!0,r(e),ce});u||(s.add(a),i=!0)})}var o=e[0],i=e[1],s=new ie;return r(o),s}function r(t,e){t(function(n){e(t,n)})}t.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,r)},t.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState([t,n],e)},t.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,r)},t.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative([t,r],e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},t.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,r)},t.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute([t,r],e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})}}(ye.prototype),function(t){ye.prototype.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,e)},ye.prototype.schedulePeriodicWithState=function(t,e,n){if("undefined"==typeof X.setInterval)throw new bt;e=be(e);var r=t,o=X.setInterval(function(){r=n(r)},e);return ae(function(){X.clearInterval(o)})}}(ye.prototype),function(t){t.catchError=t["catch"]=function(t){return new Ae(this,t)}}(ye.prototype);var ge,we,xe=(tt.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new fe;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),ye.immediate=function(){function t(t,e){return e(this,t)}return new ye(rt,t,wt,wt)}()),_e=ye.currentThread=function(){function t(){for(;n.length>0;){var t=n.dequeue();!t.isCancelled()&&t.invoke()}}function e(e,r){var o=new ve(this,e,r,this.now());if(n)n.enqueue(o);else{n=new re(4),n.enqueue(o);var i=x(t)();if(n=null,i===ne)return _(i.e)}return o.disposable}var n,r=new ye(rt,e,wt,wt);return r.scheduleRequired=function(){return!n},r}(),Se=function(){var t,e=et;if(X.setTimeout)t=X.setTimeout,e=X.clearTimeout;else{if(!X.WScript)throw new bt;t=function(t,e){X.WScript.Sleep(e),t()}}return{setTimeout:t,clearTimeout:e}}(),Ee=Se.setTimeout,Ce=Se.clearTimeout;!function(){function t(e){if(s)Ee(function(){t(e)},0);else{var n=i[e];if(n){s=!0;var r=x(n)();if(we(e),s=!1,r===ne)return _(r.e)}}}function n(){if(!X.postMessage||X.importScripts)return!1;var t=!1,e=X.onmessage;return X.onmessage=function(){t=!0},X.postMessage("","*"),X.onmessage=e,t}function r(e){"string"==typeof e.data&&e.data.substring(0,c.length)===c&&t(e.data.substring(c.length))}var o=1,i={},s=!1;we=function(t){delete i[t]};var u=RegExp("^"+String(Wt).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),a="function"==typeof(a=Z&&Y&&Z.setImmediate)&&!u.test(a)&&a;if(at(a))ge=function(e){var n=o++;return i[n]=e,a(function(){t(n)}),n};else if("undefined"!=typeof e&&"[object process]"==={}.toString.call(e))ge=function(n){var r=o++;return i[r]=n,e.nextTick(function(){t(r)}),r};else if(n()){var c="ms.rx.schedule"+Math.random();X.addEventListener?X.addEventListener("message",r,!1):X.attachEvent?X.attachEvent("onmessage",r):X.onmessage=r,ge=function(t){var e=o++;return i[e]=t,X.postMessage(c+currentId,"*"),e}}else if(X.MessageChannel){var p=new X.MessageChannel;p.port1.onmessage=function(e){t(e.data)},ge=function(t){var e=o++;return i[e]=t,p.port2.postMessage(e),e}}else ge="document"in X&&"onreadystatechange"in X.document.createElement("script")?function(e){var n=X.document.createElement("script"),r=o++;return i[r]=e,n.onreadystatechange=function(){t(r),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},X.document.documentElement.appendChild(n),r}:function(e){var n=o++;return i[n]=e,Ee(function(){t(n)},0),n}}();var Ae=(ye.timeout=ye["default"]=function(){function t(t,e){var n=this,r=new fe,o=ge(function(){!r.isDisposed&&r.setDisposable(e(n,t))});return new ie(r,ae(function(){we(o)}))}function e(t,e,n){var r=this,o=ye.normalize(e),i=new fe;if(0===o)return r.scheduleWithState(t,n);var s=Ee(function(){!i.isDisposed&&i.setDisposable(n(r,t))},o);return new ie(i,ae(function(){Ce(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ye(rt,t,e,n)}(),function(t){function e(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function n(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,i){this._scheduler=o,this._handler=i,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,this._scheduler.now.bind(this._scheduler),e,n,r)}return Zt(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(o){if(!e._handler(o))throw o;return ce}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,o=!1,i=new fe;return i.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(o)return null;try{return n(t)}catch(e){if(o=!0,!r._handler(e))throw e;return i.dispose(),null}})),i},o}(ye)),Ne=tt.Notification=function(){function t(t,e,n,r,o,i){this.kind=t,this.value=e,this.exception=n,this._accept=r,this._acceptObservable=o,this.toString=i}return t.prototype.accept=function(t,e,n){return t&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},t.prototype.toObservable=function(t){var e=this;return me(t)||(t=xe),new qn(function(n){return t.scheduleWithState(e,function(t,e){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),ke=Ne.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){return new Ne("N",r,null,t,e,n)}}(),Oe=Ne.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){return new Ne("E",null,r,t,e,n)}}(),Pe=Ne.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){return new Ne("C",null,null,t,e,n)}}(),je=tt.Observer=function(){};je.prototype.toNotifier=function(){var t=this;return function(e){return e.accept(t)}},je.prototype.asObserver=function(){return new Me(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))},je.prototype.checked=function(){return new Te(this)};var De=je.create=function(t,e,n){return t||(t=et),e||(e=st),n||(n=et),new Me(t,e,n)};je.fromNotifier=function(t,e){return new Me(function(n){return t.call(e,ke(n))},function(n){return t.call(e,Oe(n))},function(){return t.call(e,Pe())})},je.prototype.notifyOn=function(t){return new $e(t,this)},je.prototype.makeSafe=function(t){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,t)};var qe,Re=tt.internals.AbstractObserver=function(t){function e(){this.isStopped=!1,t.call(this)}return Zt(e,t),e.prototype.next=gt,e.prototype.error=gt,e.prototype.completed=gt,e.prototype.onNext=function(t){this.isStopped||this.next(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.error(t))},e.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.error(t),!0)},e}(je),Me=tt.AnonymousObserver=function(t){function e(e,n,r){t.call(this),this._onNext=e,this._onError=n,this._onCompleted=r}return Zt(e,t),e.prototype.next=function(t){this._onNext(t)},e.prototype.error=function(t){this._onError(t)},e.prototype.completed=function(){this._onCompleted()},e}(Re),Te=function(t){function e(e){t.call(this),this._observer=e,this._state=0}Zt(e,t);var n=e.prototype;return n.onNext=function(t){this.checkAccess();var e=x(this._observer.onNext).call(this._observer,t);this._state=0,e===ne&&_(e.e)},n.onError=function(t){this.checkAccess();var e=x(this._observer.onError).call(this._observer,t);this._state=2,e===ne&&_(e.e)},n.onCompleted=function(){this.checkAccess();var t=x(this._observer.onCompleted).call(this._observer);this._state=2,t===ne&&_(t.e)},n.checkAccess=function(){if(1===this._state)throw new Error("Re-entrancy detected");if(2===this._state)throw new Error("Observer completed");0===this._state&&(this._state=1)},e}(je),Ve=tt.internals.ScheduledObserver=function(t){function e(e,n){t.call(this),this.scheduler=e,this.observer=n,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new le}return Zt(e,t),e.prototype.next=function(t){var e=this;this.queue.push(function(){e.observer.onNext(t)})},e.prototype.error=function(t){var e=this;this.queue.push(function(){e.observer.onError(t)})},e.prototype.completed=function(){var t=this;this.queue.push(function(){t.observer.onCompleted()})},e.prototype.ensureActive=function(){var t=!1,e=this;!this.hasFaulted&&this.queue.length>0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var n;if(!(e.queue.length>0))return void(e.isAcquired=!1);n=e.queue.shift();try{n()}catch(r){throw e.queue=[],e.hasFaulted=!0,r}t()}))},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},e}(Re),$e=function(t){function e(e,n,r){t.call(this,e,n),this._cancel=r}return Zt(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this._cancel&&this._cancel.dispose(),this._cancel=null},e}(Ve),We=tt.Observable=function(){function t(t){if(tt.config.longStackSupport&&ct){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var n=this;this._subscribe=function(e){var r=e.onError.bind(e);return e.onError=function(t){a(t,n),r(t)},t.call(n,e)}}else this._subscribe=t}return qe=t.prototype,qe.subscribe=qe.forEach=function(t,e,n){return this._subscribe("object"==typeof t?t:De(t,e,n))},qe.subscribeOnNext=function(t,e){return this._subscribe(De("undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnError=function(t,e){return this._subscribe(De(null,"undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnCompleted=function(t,e){return this._subscribe(De(null,null,"undefined"!=typeof e?function(){t.call(e)}:t))},t}(),ze=tt.ObservableBase=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o.subscribeCore).call(o,r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(t){var e=new Rn(t),r=[e,this];return _e.scheduleRequired()?_e.scheduleWithState(r,n):n(null,r),e}function o(){t.call(this,r)}return Zt(o,t),o.prototype.subscribeCore=gt,o}(We),Ge=tt.internals.Enumerable=function(){},Je=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e,n){this.o=t,this.s=e,this.e=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,r=new le,o=xe.scheduleRecursiveWithState(this.sources[xt](),function(o,i){if(!e){var s=x(o.next).call(o);if(s===ne)return t.onError(s.e);if(s.done)return t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(new n(t,i,o)))}});return new ie(r,o,ae(function(){e=!0}))},n.prototype.onNext=function(t){this.isStopped||this.o.onNext(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.s(this.e))},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);Ge.prototype.concat=function(){return new Je(this)};var Ie=function(t){function e(e){this.sources=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,n=this.sources[xt](),r=new le,o=xe.scheduleRecursiveWithState(null,function(o,i){if(!e){var s=x(n.next).call(n);if(s===ne)return t.onError(s.e);if(s.done)return null!==o?t.onError(o):t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(function(e){t.onNext(e)},i,function(){t.onCompleted()}))}});return new ie(r,o,ae(function(){e=!0}))},e}(ze);Ge.prototype.catchError=function(){return new Ie(this)},Ge.prototype.catchErrorWhen=function(t){var e=this;return new qn(function(n){var r,o,i=new Tn,s=new Tn,u=t(i),a=u.subscribe(s),c=e[xt](),p=new le,h=xe.scheduleRecursive(function(t){if(!r){var e=x(c.next).call(c);if(e===ne)return n.onError(e.e);if(e.done)return void(o?n.onError(o):n.onCompleted());var u=e.value;ut(u)&&(u=Xe(u));var a=new fe,h=new fe;p.setDisposable(new ie(h,a)),a.setDisposable(u.subscribe(function(t){n.onNext(t)},function(e){h.setDisposable(s.subscribe(t,function(t){n.onError(t)},function(){n.onCompleted()})),i.onNext(e)},function(){n.onCompleted()}))}});return new ie(a,p,h,ae(function(){r=!0}))})};var Le=function(t){function e(t,e){this.v=t,this.c=null==e?-1:e}function n(t){this.v=t.v,this.l=t.c}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return 0===this.l?_t:(this.l>0&&this.l--,{done:!1,value:this.v})},e}(Ge),Be=Ge.repeat=function(t,e){return new Le(t,e)},Fe=function(t){function e(t,e,n){this.s=t,this.fn=e?At(e,n,3):null}function n(t){this.i=-1,this.s=t.s,this.l=this.s.length,this.fn=t.fn}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return++this.i<this.l?{done:!1,value:this.fn?this.fn(this.s[this.i],this.i,this.s):this.s[this.i]}:_t},e}(Ge),Ue=Ge.of=function(t,e,n){return new Fe(t,e,n)};qe.observeOn=function(t){var e=this;return new qn(function(n){return e.subscribe(new $e(t,n))},e)},qe.subscribeOn=function(t){var e=this;return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.schedule(function(){o.setDisposable(new E(t,e.subscribe(n)))})),o},e)};var He=function(t){function e(e){this.p=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.p.then(function(e){t.onNext(e),t.onCompleted()},function(e){t.onError(e)}),ce},e}(ze),Xe=We.fromPromise=function(t){return new He(t)};qe.toPromise=function(t){if(t||(t=tt.config.Promise),!t)throw new bt("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,o=!1;e.subscribe(function(t){r=t,o=!0},n,function(){o&&t(r)})})};var Qe=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.a=[],this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=function(t){this.isStopped||this.a.push(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onNext(this.a),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.toArray=function(){return new Qe(this)},We.create=We.createWithDisposable=function(t,e){return new qn(t,e)};var Ke=(We.defer=function(t){return new qn(function(e){var n;try{n=t()}catch(r){return dn(r).subscribe(e)}return ut(n)&&(n=Xe(n)),n.subscribe(e)})},function(t){function e(e){this.scheduler=e,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){e.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState(this.observer,r)},e}(ze)),Ye=We.empty=function(t){return me(t)||(t=xe),new Ke(t)},Ze=function(t){function e(e,n,r){this.iterable=e,this.mapper=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new tn(t,this);return e.run()},e}(ze),tn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,e){try{var i=n.next()}catch(s){return r.onError(s)}if(i.done)return r.onCompleted();var u=i.value;if(o)try{u=o(u,t)}catch(s){return r.onError(s)}r.onNext(u),e(t+1)}var e=Object(this.parent.iterable),n=j(e),r=this.observer,o=this.parent.mapper;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}(),en=Math.pow(2,53)-1;A.prototype[xt]=function(){return new N(this._s)},N.prototype[xt]=function(){return this},N.prototype.next=function(){return this._i<this._l?{done:!1,value:this._s.charAt(this._i++)}:_t},k.prototype[xt]=function(){return new O(this._a)},O.prototype[xt]=function(){return this},O.prototype.next=function(){return this._i<this._l?{done:!1,value:this._a[this._i++]}:_t};var nn=We.from=function(t,e,n,r){if(null==t)throw new Error("iterable cannot be null.");if(e&&!at(e))throw new Error("mapFn when provided must be a function");if(e)var o=At(e,n,2);return me(r)||(r=_e),new Ze(t,o,r)},rn=function(t){function e(e,n){this.args=e,this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new R(t,this);return e.run()},e}(ze);R.prototype.run=function(){function t(t,o){r>t?(e.onNext(n[t]),o(t+1)):e.onCompleted()}var e=this.observer,n=this.parent.args,r=n.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)};var on=We.fromArray=function(t,e){return me(e)||(e=_e),new rn(t,e)};We.generate=function(t,e,n,r,o){return me(o)||(o=_e),new qn(function(i){var s=!0;return o.scheduleRecursiveWithState(t,function(t,o){var u,a;try{s?s=!1:t=n(t),u=e(t),u&&(a=r(t))}catch(c){return i.onError(c)}u?(i.onNext(a),o(t)):i.onCompleted()})})};var sn=function(t){function e(){t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return ce},e}(ze),un=We.never=function(){return new sn};We.of=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return new rn(e,_e)},We.ofWithScheduler=function(t){for(var e=arguments.length,n=new Array(e-1),r=1;e>r;r++)n[r-1]=arguments[r];return new rn(n,t)};var an=function(t){function e(e,n){this.obj=e,this.keys=Object.keys(e),this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new T(t,this);return e.run()},e}(ze);T.prototype.run=function(){function t(t,i){if(o>t){var s=r[t];e.onNext([s,n[s]]),i(t+1)}else e.onCompleted()}var e=this.observer,n=this.parent.obj,r=this.parent.keys,o=r.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},We.pairs=function(t,e){return e||(e=_e),new an(t,e)};var cn=function(t){function e(e,n,r){this.start=e,this.rangeCount=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new pn(t,this);return e.run()},e}(ze),pn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,o){n>t?(r.onNext(e+t),o(t+1)):r.onCompleted()}var e=this.parent.start,n=this.parent.rangeCount,r=this.observer;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}();We.range=function(t,e,n){return me(n)||(n=_e),new cn(t,e,n)};var hn=function(t){function e(e,n,r){this.value=e,this.repeatCount=null==n?-1:n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new V(t,this);return e.run()},e}(ze);V.prototype.run=function(){function t(t,r){return(-1===t||t>0)&&(e.onNext(n),t>0&&t--),0===t?e.onCompleted():void r(t)}var e=this.observer,n=this.parent.value;return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,t)},We.repeat=function(t,e,n){return me(n)||(n=_e),new hn(t,e,n)};var fn=function(t){function e(e,n){this.value=e,this.scheduler=n,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){var n=e[0],r=e[1];r.onNext(n),r.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],r)},e}(ze),ln=(We["return"]=We.just=We.returnValue=function(t,e){return me(e)||(e=xe),new fn(t,e)},function(t){function e(e,n){this.error=e,this.scheduler=n,t.call(this)}function n(t,e){this.o=t,this.p=e}function r(t,e){var n=e[0],r=e[1];r.onError(n)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],r)},e}(ze)),dn=We["throw"]=We.throwError=We.throwException=function(t,e){return me(e)||(e=xe),new ln(t,e)};We.using=function(t,e){return new qn(function(n){var r,o,i=ce;try{r=t(),r&&(i=r),o=e(r)}catch(s){return new ie(dn(s).subscribe(n),i)}return new ie(o.subscribe(n),i)})},qe.amb=function(t){var e=this;return new qn(function(n){function r(){i||(i=s,c.dispose())}function o(){i||(i=u,a.dispose())}var i,s="L",u="R",a=new fe,c=new fe;return ut(t)&&(t=Xe(t)),a.setDisposable(e.subscribe(function(t){r(),i===s&&n.onNext(t)},function(t){r(),i===s&&n.onError(t)},function(){r(),i===s&&n.onCompleted()})),c.setDisposable(t.subscribe(function(t){o(),i===u&&n.onNext(t)},function(t){o(),i===u&&n.onError(t)},function(){o(),i===u&&n.onCompleted()})),new ie(a,c)})},We.amb=function(){function t(t,e){return t.amb(e)}var e=un(),n=[];if(Array.isArray(arguments[0]))n=arguments[0];else for(var r=0,o=arguments.length;o>r;r++)n.push(arguments[r]);for(var r=0,o=n.length;o>r;r++)e=t(e,n[r]);return e},qe["catch"]=qe.catchError=qe.catchException=function(t){return"function"==typeof t?$(this,t):vn([this,t])};var vn=We.catchError=We["catch"]=We.catchException=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return Ue(t).catchError()};qe.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return Array.isArray(e[0])?e[0].unshift(this):e.unshift(this),yn.apply(this,e)};var yn=We.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop();return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){function n(e){if(u[e]=!0,a||(a=u.every(nt))){try{var n=r.apply(null,p)}catch(o){return t.onError(o)}t.onNext(n)}else c.filter(function(t,n){return n!==e}).every(nt)&&t.onCompleted()}function o(e){c[e]=!0,c.every(nt)&&t.onCompleted()}for(var i=e.length,s=function(){return!1},u=g(i,s),a=!1,c=g(i,s),p=new Array(i),h=new Array(i),f=0;i>f;f++)!function(r){var i=e[r],s=new fe;ut(i)&&(i=Xe(i)),s.setDisposable(i.subscribe(function(t){p[r]=t,n(r)},function(e){t.onError(e)},function(){o(r)})),h[r]=s}(f);return new ie(h)},this)};qe.concat=function(){for(var t=[],e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return t.unshift(this),mn.apply(null,t)};var bn=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e){this.sources=t,this.o=e}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(this.sources,t);return e.run()},n.prototype.run=function(){var t,e=new le,n=this.sources,r=n.length,o=this.o,i=xe.scheduleRecursiveWithState(0,function(i,s){if(!t){if(i===r)return o.onCompleted();var u=n[i];ut(u)&&(u=Xe(u));var a=new fe;e.setDisposable(a),a.setDisposable(u.subscribe(function(t){o.onNext(t)},function(t){o.onError(t)},function(){s(i+1)}))}});return new ie(e,i,ae(function(){t=!0}))},e}(ze),mn=We.concat=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{t=new Array(arguments.length);for(var e=0,n=arguments.length;n>e;e++)t[e]=arguments[e]}return new bn(t)};qe.concatAll=qe.concatObservable=function(){return this.merge(1)};var gn=function(t){function e(e,n){this.source=e,this.maxConcurrent=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie;return e.add(this.source.subscribe(new wn(t,this.maxConcurrent,e))),e},e}(ze),wn=function(){function t(t,e,n){this.o=t,this.max=e,this.g=n,this.done=!1,this.q=[],this.activeCount=0,this.isStopped=!1}function e(t,e){this.parent=t,this.sad=e,this.isStopped=!1}return t.prototype.handleSubscribe=function(t){var n=new fe;this.g.add(n),ut(t)&&(t=Xe(t)),n.setDisposable(t.subscribe(new e(this,n)))},t.prototype.onNext=function(t){this.isStopped||(this.activeCount<this.max?(this.activeCount++,this.handleSubscribe(t)):this.q.push(t))},t.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},t.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,0===this.activeCount&&this.o.onCompleted())},t.prototype.dispose=function(){this.isStopped=!0},t.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},e.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=this.parent;t.g.remove(this.sad),t.q.length>0?t.handleSubscribe(t.q.shift()):(t.activeCount--,t.done&&0===t.activeCount&&t.o.onCompleted())}},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},t}();qe.merge=function(t){return"number"!=typeof t?xn(this,t):new gn(this,t)};var xn=We.merge=function(){var t,e,n=[],r=arguments.length;if(arguments[0])if(me(arguments[0]))for(t=arguments[0],e=1;r>e;e++)n.push(arguments[e]);else for(t=xe,e=0;r>e;e++)n.push(arguments[e]);else for(t=xe,e=1;r>e;e++)n.push(arguments[e]);return Array.isArray(n[0])&&(n=n[0]),M(t,n).mergeAll()},_n=tt.CompositeError=function(t){this.name="NotImplementedError",this.innerErrors=t,this.message="This contains multiple errors. Check the innerErrors",Error.call(this)};_n.prototype=Error.prototype,We.mergeDelayError=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}var r=M(null,t);return new qn(function(t){function e(){0===s.length?t.onCompleted():1===s.length?t.onError(s[0]):t.onError(new _n(s))}var n=new ie,o=new fe,i=!1,s=[];return n.add(o),o.setDisposable(r.subscribe(function(r){var o=new fe;n.add(o),ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(e){t.onNext(e)},function(t){s.push(t),n.remove(o),i&&1===n.length&&e()},function(){n.remove(o),i&&1===n.length&&e()}))},function(t){s.push(t),i=!0,1===n.length&&e()},function(){i=!0,1===n.length&&e()})),n})};var Sn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.g=e,this.isStopped=!1,this.done=!1}function r(t,e,n){this.parent=t,this.g=e,this.sad=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie,r=new fe;return e.add(r),r.setDisposable(this.source.subscribe(new n(t,e))),e},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe;this.g.add(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,this.g,e)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,1===this.g.length&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},r.prototype.onCompleted=function(){if(!this.isStopped){var t=this.parent;this.isStopped=!0,t.g.remove(this.sad),t.done&&1===t.g.length&&t.o.onCompleted()}},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe.mergeAll=qe.mergeObservable=function(){
3459 return new Sn(this)},qe.onErrorResumeNext=function(t){if(!t)throw new Error("Second observable is required");return En([this,t])};var En=We.onErrorResumeNext=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return new qn(function(e){var n=0,r=new le,o=xe.scheduleRecursive(function(o){var i,s;n<t.length?(i=t[n++],ut(i)&&(i=Xe(i)),s=new fe,r.setDisposable(s),s.setDisposable(i.subscribe(e.onNext.bind(e),o,o))):e.onCompleted()});return new ie(r,o)})};qe.skipUntil=function(t){var e=this;return new qn(function(n){var r=!1,o=new ie(e.subscribe(function(t){r&&n.onNext(t)},function(t){n.onError(t)},function(){r&&n.onCompleted()}));ut(t)&&(t=Xe(t));var i=new fe;return o.add(i),i.setDisposable(t.subscribe(function(){r=!0,i.dispose()},function(t){n.onError(t)},function(){i.dispose()})),o},e)};var Cn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.inner=e,this.stopped=!1,this.latest=0,this.hasLatest=!1,this.isStopped=!1}function r(t,e){this.parent=t,this.id=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new le,r=this.source.subscribe(new n(t,e));return new ie(r,e)},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe,n=++this.latest;this.hasLatest=!0,this.inner.setDisposable(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,n)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.stopped=!0,!this.hasLatest&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.latest===this.id&&this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&this.parent.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&(this.parent.hasLatest=!1,this.parent.isStopped&&this.parent.o.onCompleted()))},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe["switch"]=qe.switchLatest=function(){return new Cn(this)};var An=function(t){function e(e,n){this.source=e,this.other=ut(n)?Xe(n):n,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return new ie(this.source.subscribe(t),this.other.subscribe(new n(t)))},n.prototype.onNext=function(t){this.isStopped||this.o.onCompleted()},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){!this.isStopped&&(this.isStopped=!0)},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.takeUntil=function(t){return new An(this,t)},qe.withLatestFrom=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop(),o=this;return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){for(var n=e.length,i=g(n,W),s=!1,u=new Array(n),a=new Array(n+1),c=0;n>c;c++)!function(n){var r=e[n],o=new fe;ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(t){u[n]=t,i[n]=!0,s=i.every(nt)},function(e){t.onError(e)},et)),a[n]=o}(c);var p=new fe;return p.setDisposable(o.subscribe(function(e){var n=[e].concat(u);if(s){var o=x(r).apply(null,n);return o===ne?t.onError(o.e):void t.onNext(o)}},function(e){t.onError(e)},function(){t.onCompleted()})),a[n]=p,new ie(a)},this)},qe.zip=function(){if(Array.isArray(arguments[0]))return z.apply(this,arguments);for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=this,o=e.pop();return e.unshift(r),new qn(function(t){for(var n=e.length,i=g(n,G),s=g(n,W),u=new Array(n),a=0;n>a;a++)!function(n){var a=e[n],c=new fe;ut(a)&&(a=Xe(a)),c.setDisposable(a.subscribe(function(e){if(i[n].push(e),i.every(function(t){return t.length>0})){var u=i.map(function(t){return t.shift()}),a=x(o).apply(r,u);if(a===ne)return t.onError(a.e);t.onNext(a)}else s.filter(function(t,e){return e!==n}).every(nt)&&t.onCompleted()},function(e){t.onError(e)},function(){s[n]=!0,s.every(nt)&&t.onCompleted()})),u[n]=c}(a);return new ie(u)},r)},We.zip=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.shift();return r.zip.apply(r,e)},We.zipArray=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}return new qn(function(e){for(var n=t.length,r=g(n,J),o=g(n,W),i=new Array(n),s=0;n>s;s++)!function(n){i[n]=new fe,i[n].setDisposable(t[n].subscribe(function(t){if(r[n].push(t),r.every(function(t){return t.length>0})){var i=r.map(function(t){return t.shift()});e.onNext(i)}else if(o.filter(function(t,e){return e!==n}).every(nt))return e.onCompleted()},function(t){e.onError(t)},function(){o[n]=!0,o.every(nt)&&e.onCompleted()}))}(s);return new ie(i)})},qe.asObservable=function(){var t=this;return new qn(function(e){return t.subscribe(e)},t)},qe.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},qe.dematerialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){return t.accept(e)},function(t){e.onError(t)},function(){e.onCompleted()})},this)},qe.distinctUntilChanged=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o,i=!1;return n.subscribe(function(n){var s=n;if(t&&(s=x(t)(n),s===ne))return r.onError(s.e);if(i){var u=x(e)(o,s);if(u===ne)return r.onError(u.e)}i&&u||(i=!0,o=s,r.onNext(n))},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Nn=function(t){function e(e,n,r,o){this.source=e,this.t=!n||at(n)?De(n||et,r||et,o||et):n,t.call(this)}function n(t,e){this.o=t,this.t=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.t))},n.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.t.onNext).call(this.t,t);e===ne&&this.o.onError(e.e),this.o.onNext(t)}},n.prototype.onError=function(t){if(!this.isStopped){this.isStopped=!0;var e=x(this.t.onError).call(this.t,t);if(e===ne)return this.o.onError(e.e);this.o.onError(t)}},n.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=x(this.t.onCompleted).call(this.t);if(t===ne)return this.o.onError(t.e);this.o.onCompleted()}},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe["do"]=qe.tap=qe.doAction=function(t,e,n){return new Nn(this,t,e,n)},qe.doOnNext=qe.tapOnNext=function(t,e){return this.tap("undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnError=qe.tapOnError=function(t,e){return this.tap(et,"undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnCompleted=qe.tapOnCompleted=function(t,e){return this.tap(et,null,"undefined"!=typeof e?function(){t.call(e)}:t)},qe["finally"]=qe.ensure=function(t){var e=this;return new qn(function(n){var r;try{r=e.subscribe(n)}catch(o){throw t(),o}return ae(function(){try{r.dispose()}catch(e){throw e}finally{t()}})},this)},qe.finallyAction=function(t){return this.ensure(t)};var kn=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=et,n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},e}(ze);qe.ignoreElements=function(){return new kn(this)},qe.materialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){e.onNext(ke(t))},function(t){e.onNext(Oe(t)),e.onCompleted()},function(){e.onNext(Pe()),e.onCompleted()})},t)},qe.repeat=function(t){return Be(this,t).concat()},qe.retry=function(t){return Be(this,t).catchError()},qe.retryWhen=function(t){return Be(this).catchErrorWhen(t)};var On=function(t){function e(e,n,r,o){this.source=e,this.accumulator=n,this.hasSeed=r,this.seed=o,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new I(t,this))},e}(ze);I.prototype.onNext=function(t){if(!this.isStopped){!this.hasValue&&(this.hasValue=!0);try{this.hasAccumulation?this.accumulation=this.accumulator(this.accumulation,t):(this.accumulation=this.hasSeed?this.accumulator(this.seed,t):t,this.hasAccumulation=!0)}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)}},I.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.observer.onError(t))},I.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed),this.observer.onCompleted())},I.prototype.dispose=function(){this.isStopped=!0},I.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},qe.scan=function(){var t,e,n=!1;return 2===arguments.length?(n=!0,t=arguments[0],e=arguments[1]):e=arguments[0],new On(this,e,n,t)},qe.skipLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},function(t){n.onError(t)},function(){n.onCompleted()})},e)},qe.startWith=function(){var t,e=0;arguments.length&&me(arguments[0])?(t=arguments[0],e=1):t=xe;for(var n=[],r=e,o=arguments.length;o>r;r++)n.push(arguments[r]);return Ue([on(n,t),this]).concat()},qe.takeLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){for(;r.length>0;)n.onNext(r.shift());n.onCompleted()})},e)},qe.takeLastBuffer=function(t){var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},qe.windowWithCount=function(t,e){var n=this;if(+t||(t=0),Math.abs(t)===1/0&&(t=0),0>=t)throw new yt;if(null==e&&(e=t),+e||(e=0),Math.abs(e)===1/0&&(e=0),0>=e)throw new yt;return new qn(function(r){function o(){var t=new Tn;a.push(t),r.onNext(ee(t,s))}var i=new fe,s=new de(i),u=0,a=[];return o(),i.setDisposable(n.subscribe(function(n){for(var r=0,i=a.length;i>r;r++)a[r].onNext(n);var s=u-t+1;s>=0&&s%e===0&&a.shift().onCompleted(),++u%e===0&&o()},function(t){for(;a.length>0;)a.shift().onError(t);r.onError(t)},function(){for(;a.length>0;)a.shift().onCompleted();r.onCompleted()})),s},n)},qe.selectConcat=qe.concatMap=function(t,e,n){return at(t)&&at(e)?this.concatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})}):at(t)?L(this,t,n):L(this,function(){return t})},qe.concatMapObserver=qe.selectConcatObserver=function(t,e,n,r){var o=this,i=At(t,r,2),s=At(e,r,1),u=At(n,r,0);return new qn(function(t){var e=0;return o.subscribe(function(n){var r;try{r=i(n,e++)}catch(o){return void t.onError(o)}ut(r)&&(r=Xe(r)),t.onNext(r)},function(e){var n;try{n=s(e)}catch(r){return void t.onError(r)}ut(n)&&(n=Xe(n)),t.onNext(n),t.onCompleted()},function(){var e;try{e=u()}catch(n){return void t.onError(n)}ut(e)&&(e=Xe(e)),t.onNext(e),t.onCompleted()})},this).concatAll()},qe.defaultIfEmpty=function(t){var e=this;return t===i&&(t=null),new qn(function(n){var r=!1;return e.subscribe(function(t){r=!0,n.onNext(t)},function(t){n.onError(t)},function(){!r&&n.onNext(t),n.onCompleted()})},e)},F.prototype.push=function(t){var e=-1===B(this.set,t,this.comparer);return e&&this.set.push(t),e},qe.distinct=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o=new F(e);return n.subscribe(function(e){var n=e;if(t)try{n=t(e)}catch(i){return void r.onError(i)}o.push(n)&&r.onNext(e)},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Pn=function(t){function e(e,n,r){this.source=e,this.selector=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return t.call(this,e.selector(n,r,o),r,o)}}function r(t,e,n){this.o=t,this.selector=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.internalMap=function(t,r){return new e(this.source,n(t,this),r)},e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.selector,this))},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.selector)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void this.o.onNext(e)}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.map=qe.select=function(t,e){var n="function"==typeof t?t:function(){return t};return this instanceof Pn?this.internalMap(n,e):new Pn(this,n,e)},qe.pluck=function(){var t=arguments,e=arguments.length;if(0===e)throw new Error("List of properties cannot be empty.");return this.map(function(n){for(var r=n,o=0;e>o;o++){var s=r[t[o]];if("undefined"==typeof s)return i;r=s}return r})},qe.flatMapObserver=qe.selectManyObserver=function(t,e,n,r){var o=this;return new qn(function(i){var s=0;return o.subscribe(function(e){var n;try{n=t.call(r,e,s++)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n)},function(t){var n;try{n=e.call(r,t)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n),i.onCompleted()},function(){var t;try{t=n.call(r)}catch(e){return void i.onError(e)}ut(t)&&(t=Xe(t)),i.onNext(t),i.onCompleted()})},o).mergeAll()},qe.selectMany=qe.flatMap=function(t,e,n){return at(t)&&at(e)?this.flatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})},n):at(t)?U(this,t,n):U(this,function(){return t})},qe.selectSwitch=qe.flatMapLatest=qe.switchMap=function(t,e){return this.select(t,e).switchLatest()};var jn=function(t){function e(e,n){this.source=e,this.skipCount=n,t.call(this)}function n(t,e){this.c=e,this.r=e,this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.skipCount))},n.prototype.onNext=function(t){this.isStopped||(this.r<=0?this.o.onNext(t):this.r--)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.skip=function(t){if(0>t)throw new yt;return new jn(this,t)},qe.skipWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!1;return n.subscribe(function(i){if(!o)try{o=!r(i,e++,n)}catch(s){return void t.onError(s)}o&&t.onNext(i)},function(e){t.onError(e)},function(){t.onCompleted()})},n)},qe.take=function(t,e){if(0>t)throw new yt;if(0===t)return Ye(e);var n=this;return new qn(function(e){var r=t;return n.subscribe(function(t){r-- >0&&(e.onNext(t),0>=r&&e.onCompleted())},function(t){e.onError(t)},function(){e.onCompleted()})},n)},qe.takeWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!0;return n.subscribe(function(i){if(o){try{o=r(i,e++,n)}catch(s){return void t.onError(s)}o?t.onNext(i):t.onCompleted()}},function(e){t.onError(e)},function(){t.onCompleted()})},n)};var Dn=function(t){function e(e,n,r){this.source=e,this.predicate=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return e.predicate(n,r,o)&&t.call(this,n,r,o)}}function r(t,e,n){this.o=t,this.predicate=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.predicate,this))},e.prototype.internalFilter=function(t,r){return new e(this.source,n(t,this),r)},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.predicate)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void(e&&this.o.onNext(t))}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.filter=qe.where=function(t,e){return this instanceof Dn?this.internalFilter(t,e):new Dn(this,t,e)},qe.transduce=function(t){function e(t){return{"@@transducer/init":function(){return t},"@@transducer/step":function(t,e){return t.onNext(e)},"@@transducer/result":function(t){return t.onCompleted()}}}var n=this;return new qn(function(r){var o=t(e(r));return n.subscribe(function(t){try{o["@@transducer/step"](r,t)}catch(e){r.onError(e)}},function(t){r.onError(t)},function(){o["@@transducer/result"](r)})},n)};var qn=tt.AnonymousObservable=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o)(r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(e,r){function o(t){var r=new Rn(t),o=[r,e];return _e.scheduleRequired()?_e.scheduleWithState(o,n):n(null,o),r}this.source=r,t.call(this,o)}return Zt(r,t),r}(We),Rn=function(t){function e(e){t.call(this),this.observer=e,this.m=new fe}Zt(e,t);var n=e.prototype;return n.next=function(t){var e=x(this.observer.onNext).call(this.observer,t);e===ne&&(this.dispose(),_(e.e))},n.error=function(t){var e=x(this.observer.onError).call(this.observer,t);this.dispose(),e===ne&&_(e.e)},n.completed=function(){var t=x(this.observer.onCompleted).call(this.observer);this.dispose(),t===ne&&_(t.e)},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Re),Mn=function(t,e){this.subject=t,this.observer=e};Mn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Tn=tt.Subject=function(t){function e(t){return he(this),this.isStopped?this.hasError?(t.onError(this.error),ce):(t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(he(this),!this.isStopped){this.isStopped=!0;for(var t=0,e=u(this.observers),n=e.length;n>t;t++)e[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){if(he(this),!this.isStopped)for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Vn(t,e)},n}(We),Vn=(tt.AsyncSubject=function(t){function e(t){return he(this),this.isStopped?(this.hasError?t.onError(this.error):this.hasValue?(t.onNext(this.value),t.onCompleted()):t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.hasValue=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je,{hasObservers:function(){return he(this),this.observers.length>0},onCompleted:function(){var t,e;if(he(this),!this.isStopped){this.isStopped=!0;var n=u(this.observers),e=n.length;if(this.hasValue)for(t=0;e>t;t++){var r=n[t];r.onNext(this.value),r.onCompleted()}else for(t=0;e>t;t++)n[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.hasError=!0,this.error=t;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){he(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(We),tt.AnonymousSubject=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){this.observer=n,this.observable=r,t.call(this,e)}return Zt(n,t),te(n.prototype,je.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(We));"function"==typeof t&&"object"==typeof t.amd&&t.amd?(X.Rx=tt,t(function(){return tt})):Q&&K?Y?(K.exports=tt).Rx=tt:Q.Rx=tt:X.Rx=tt;var $n=f()}).call(this)}).call(this,e(150),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{150:150}]},{},[1])(1)});
3460 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3461
3462 },{}],16:[function(require,module,exports){
3463 (function (global){
3464 var topLevel = typeof global !== 'undefined' ? global :
3465     typeof window !== 'undefined' ? window : {}
3466 var minDoc = require('min-document');
3467
3468 var doccy;
3469
3470 if (typeof document !== 'undefined') {
3471     doccy = document;
3472 } else {
3473     doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3474
3475     if (!doccy) {
3476         doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3477     }
3478 }
3479
3480 module.exports = doccy;
3481
3482 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3483
3484 },{"min-document":4}],17:[function(require,module,exports){
3485 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3486   var e, m
3487   var eLen = nBytes * 8 - mLen - 1
3488   var eMax = (1 << eLen) - 1
3489   var eBias = eMax >> 1
3490   var nBits = -7
3491   var i = isLE ? (nBytes - 1) : 0
3492   var d = isLE ? -1 : 1
3493   var s = buffer[offset + i]
3494
3495   i += d
3496
3497   e = s & ((1 << (-nBits)) - 1)
3498   s >>= (-nBits)
3499   nBits += eLen
3500   for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3501
3502   m = e & ((1 << (-nBits)) - 1)
3503   e >>= (-nBits)
3504   nBits += mLen
3505   for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3506
3507   if (e === 0) {
3508     e = 1 - eBias
3509   } else if (e === eMax) {
3510     return m ? NaN : ((s ? -1 : 1) * Infinity)
3511   } else {
3512     m = m + Math.pow(2, mLen)
3513     e = e - eBias
3514   }
3515   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3516 }
3517
3518 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3519   var e, m, c
3520   var eLen = nBytes * 8 - mLen - 1
3521   var eMax = (1 << eLen) - 1
3522   var eBias = eMax >> 1
3523   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3524   var i = isLE ? 0 : (nBytes - 1)
3525   var d = isLE ? 1 : -1
3526   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3527
3528   value = Math.abs(value)
3529
3530   if (isNaN(value) || value === Infinity) {
3531     m = isNaN(value) ? 1 : 0
3532     e = eMax
3533   } else {
3534     e = Math.floor(Math.log(value) / Math.LN2)
3535     if (value * (c = Math.pow(2, -e)) < 1) {
3536       e--
3537       c *= 2
3538     }
3539     if (e + eBias >= 1) {
3540       value += rt / c
3541     } else {
3542       value += rt * Math.pow(2, 1 - eBias)
3543     }
3544     if (value * c >= 2) {
3545       e++
3546       c /= 2
3547     }
3548
3549     if (e + eBias >= eMax) {
3550       m = 0
3551       e = eMax
3552     } else if (e + eBias >= 1) {
3553       m = (value * c - 1) * Math.pow(2, mLen)
3554       e = e + eBias
3555     } else {
3556       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3557       e = 0
3558     }
3559   }
3560
3561   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3562
3563   e = (e << mLen) | m
3564   eLen += mLen
3565   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3566
3567   buffer[offset + i - d] |= s * 128
3568 }
3569
3570 },{}],18:[function(require,module,exports){
3571 (function (global){
3572 'use strict';
3573
3574 /*global window, global*/
3575
3576 var root = typeof window !== 'undefined' ?
3577     window : typeof global !== 'undefined' ?
3578     global : {};
3579
3580 module.exports = Individual;
3581
3582 function Individual(key, value) {
3583     if (key in root) {
3584         return root[key];
3585     }
3586
3587     root[key] = value;
3588
3589     return value;
3590 }
3591
3592 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3593
3594 },{}],19:[function(require,module,exports){
3595 'use strict';
3596
3597 var Individual = require('./index.js');
3598
3599 module.exports = OneVersion;
3600
3601 function OneVersion(moduleName, version, defaultValue) {
3602     var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3603     var enforceKey = key + '_ENFORCE_SINGLETON';
3604
3605     var versionValue = Individual(enforceKey, version);
3606
3607     if (versionValue !== version) {
3608         throw new Error('Can only have one copy of ' +
3609             moduleName + '.\n' +
3610             'You already have version ' + versionValue +
3611             ' installed.\n' +
3612             'This means you cannot install version ' + version);
3613     }
3614
3615     return Individual(key, defaultValue);
3616 }
3617
3618 },{"./index.js":18}],20:[function(require,module,exports){
3619 "use strict";
3620
3621 module.exports = function isObject(x) {
3622         return typeof x === "object" && x !== null;
3623 };
3624
3625 },{}],21:[function(require,module,exports){
3626 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3627 /* Geohash encoding/decoding and associated functions   (c) Chris Veness 2014-2016 / MIT Licence  */
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3629
3630 'use strict';
3631
3632
3633 /**
3634  * Geohash encode, decode, bounds, neighbours.
3635  *
3636  * @namespace
3637  */
3638 var Geohash = {};
3639
3640 /* (Geohash-specific) Base32 map */
3641 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3642
3643 /**
3644  * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3645  * evaluated precision.
3646  *
3647  * @param   {number} lat - Latitude in degrees.
3648  * @param   {number} lon - Longitude in degrees.
3649  * @param   {number} [precision] - Number of characters in resulting geohash.
3650  * @returns {string} Geohash of supplied latitude/longitude.
3651  * @throws  Invalid geohash.
3652  *
3653  * @example
3654  *     var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3655  */
3656 Geohash.encode = function(lat, lon, precision) {
3657     // infer precision?
3658     if (typeof precision == 'undefined') {
3659         // refine geohash until it matches precision of supplied lat/lon
3660         for (var p=1; p<=12; p++) {
3661             var hash = Geohash.encode(lat, lon, p);
3662             var posn = Geohash.decode(hash);
3663             if (posn.lat==lat && posn.lon==lon) return hash;
3664         }
3665         precision = 12; // set to maximum
3666     }
3667
3668     lat = Number(lat);
3669     lon = Number(lon);
3670     precision = Number(precision);
3671
3672     if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3673
3674     var idx = 0; // index into base32 map
3675     var bit = 0; // each char holds 5 bits
3676     var evenBit = true;
3677     var geohash = '';
3678
3679     var latMin =  -90, latMax =  90;
3680     var lonMin = -180, lonMax = 180;
3681
3682     while (geohash.length < precision) {
3683         if (evenBit) {
3684             // bisect E-W longitude
3685             var lonMid = (lonMin + lonMax) / 2;
3686             if (lon >= lonMid) {
3687                 idx = idx*2 + 1;
3688                 lonMin = lonMid;
3689             } else {
3690                 idx = idx*2;
3691                 lonMax = lonMid;
3692             }
3693         } else {
3694             // bisect N-S latitude
3695             var latMid = (latMin + latMax) / 2;
3696             if (lat >= latMid) {
3697                 idx = idx*2 + 1;
3698                 latMin = latMid;
3699             } else {
3700                 idx = idx*2;
3701                 latMax = latMid;
3702             }
3703         }
3704         evenBit = !evenBit;
3705
3706         if (++bit == 5) {
3707             // 5 bits gives us a character: append it and start over
3708             geohash += Geohash.base32.charAt(idx);
3709             bit = 0;
3710             idx = 0;
3711         }
3712     }
3713
3714     return geohash;
3715 };
3716
3717
3718 /**
3719  * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3720  *     to reasonable precision).
3721  *
3722  * @param   {string} geohash - Geohash string to be converted to latitude/longitude.
3723  * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3724  * @throws  Invalid geohash.
3725  *
3726  * @example
3727  *     var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3728  */
3729 Geohash.decode = function(geohash) {
3730
3731     var bounds = Geohash.bounds(geohash); // <-- the hard work
3732     // now just determine the centre of the cell...
3733
3734     var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3735     var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3736
3737     // cell centre
3738     var lat = (latMin + latMax)/2;
3739     var lon = (lonMin + lonMax)/2;
3740
3741     // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3742     lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3743     lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3744
3745     return { lat: Number(lat), lon: Number(lon) };
3746 };
3747
3748
3749 /**
3750  * Returns SW/NE latitude/longitude bounds of specified geohash.
3751  *
3752  * @param   {string} geohash - Cell that bounds are required of.
3753  * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3754  * @throws  Invalid geohash.
3755  */
3756 Geohash.bounds = function(geohash) {
3757     if (geohash.length === 0) throw new Error('Invalid geohash');
3758
3759     geohash = geohash.toLowerCase();
3760
3761     var evenBit = true;
3762     var latMin =  -90, latMax =  90;
3763     var lonMin = -180, lonMax = 180;
3764
3765     for (var i=0; i<geohash.length; i++) {
3766         var chr = geohash.charAt(i);
3767         var idx = Geohash.base32.indexOf(chr);
3768         if (idx == -1) throw new Error('Invalid geohash');
3769
3770         for (var n=4; n>=0; n--) {
3771             var bitN = idx >> n & 1;
3772             if (evenBit) {
3773                 // longitude
3774                 var lonMid = (lonMin+lonMax) / 2;
3775                 if (bitN == 1) {
3776                     lonMin = lonMid;
3777                 } else {
3778                     lonMax = lonMid;
3779                 }
3780             } else {
3781                 // latitude
3782                 var latMid = (latMin+latMax) / 2;
3783                 if (bitN == 1) {
3784                     latMin = latMid;
3785                 } else {
3786                     latMax = latMid;
3787                 }
3788             }
3789             evenBit = !evenBit;
3790         }
3791     }
3792
3793     var bounds = {
3794         sw: { lat: latMin, lon: lonMin },
3795         ne: { lat: latMax, lon: lonMax },
3796     };
3797
3798     return bounds;
3799 };
3800
3801
3802 /**
3803  * Determines adjacent cell in given direction.
3804  *
3805  * @param   geohash - Cell to which adjacent cell is required.
3806  * @param   direction - Direction from geohash (N/S/E/W).
3807  * @returns {string} Geocode of adjacent cell.
3808  * @throws  Invalid geohash.
3809  */
3810 Geohash.adjacent = function(geohash, direction) {
3811     // based on github.com/davetroy/geohash-js
3812
3813     geohash = geohash.toLowerCase();
3814     direction = direction.toLowerCase();
3815
3816     if (geohash.length === 0) throw new Error('Invalid geohash');
3817     if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3818
3819     var neighbour = {
3820         n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3821         s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3822         e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3823         w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3824     };
3825     var border = {
3826         n: [ 'prxz',     'bcfguvyz' ],
3827         s: [ '028b',     '0145hjnp' ],
3828         e: [ 'bcfguvyz', 'prxz'     ],
3829         w: [ '0145hjnp', '028b'     ],
3830     };
3831
3832     var lastCh = geohash.slice(-1);    // last character of hash
3833     var parent = geohash.slice(0, -1); // hash without last character
3834
3835     var type = geohash.length % 2;
3836
3837     // check for edge-cases which don't share common prefix
3838     if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3839         parent = Geohash.adjacent(parent, direction);
3840     }
3841
3842     // append letter for direction to parent
3843     return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3844 };
3845
3846
3847 /**
3848  * Returns all 8 adjacent cells to specified geohash.
3849  *
3850  * @param   {string} geohash - Geohash neighbours are required of.
3851  * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3852  * @throws  Invalid geohash.
3853  */
3854 Geohash.neighbours = function(geohash) {
3855     return {
3856         'n':  Geohash.adjacent(geohash, 'n'),
3857         'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3858         'e':  Geohash.adjacent(geohash, 'e'),
3859         'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3860         's':  Geohash.adjacent(geohash, 's'),
3861         'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3862         'w':  Geohash.adjacent(geohash, 'w'),
3863         'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3864     };
3865 };
3866
3867
3868 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3869 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3870
3871 },{}],22:[function(require,module,exports){
3872 (function (process){
3873 // Copyright Joyent, Inc. and other Node contributors.
3874 //
3875 // Permission is hereby granted, free of charge, to any person obtaining a
3876 // copy of this software and associated documentation files (the
3877 // "Software"), to deal in the Software without restriction, including
3878 // without limitation the rights to use, copy, modify, merge, publish,
3879 // distribute, sublicense, and/or sell copies of the Software, and to permit
3880 // persons to whom the Software is furnished to do so, subject to the
3881 // following conditions:
3882 //
3883 // The above copyright notice and this permission notice shall be included
3884 // in all copies or substantial portions of the Software.
3885 //
3886 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3887 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3888 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3889 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3890 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3891 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3892 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3893
3894 // resolves . and .. elements in a path array with directory names there
3895 // must be no slashes, empty elements, or device names (c:\) in the array
3896 // (so also no leading and trailing slashes - it does not distinguish
3897 // relative and absolute paths)
3898 function normalizeArray(parts, allowAboveRoot) {
3899   // if the path tries to go above the root, `up` ends up > 0
3900   var up = 0;
3901   for (var i = parts.length - 1; i >= 0; i--) {
3902     var last = parts[i];
3903     if (last === '.') {
3904       parts.splice(i, 1);
3905     } else if (last === '..') {
3906       parts.splice(i, 1);
3907       up++;
3908     } else if (up) {
3909       parts.splice(i, 1);
3910       up--;
3911     }
3912   }
3913
3914   // if the path is allowed to go above the root, restore leading ..s
3915   if (allowAboveRoot) {
3916     for (; up--; up) {
3917       parts.unshift('..');
3918     }
3919   }
3920
3921   return parts;
3922 }
3923
3924 // Split a filename into [root, dir, basename, ext], unix version
3925 // 'root' is just a slash, or nothing.
3926 var splitPathRe =
3927     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3928 var splitPath = function(filename) {
3929   return splitPathRe.exec(filename).slice(1);
3930 };
3931
3932 // path.resolve([from ...], to)
3933 // posix version
3934 exports.resolve = function() {
3935   var resolvedPath = '',
3936       resolvedAbsolute = false;
3937
3938   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3939     var path = (i >= 0) ? arguments[i] : process.cwd();
3940
3941     // Skip empty and invalid entries
3942     if (typeof path !== 'string') {
3943       throw new TypeError('Arguments to path.resolve must be strings');
3944     } else if (!path) {
3945       continue;
3946     }
3947
3948     resolvedPath = path + '/' + resolvedPath;
3949     resolvedAbsolute = path.charAt(0) === '/';
3950   }
3951
3952   // At this point the path should be resolved to a full absolute path, but
3953   // handle relative paths to be safe (might happen when process.cwd() fails)
3954
3955   // Normalize the path
3956   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3957     return !!p;
3958   }), !resolvedAbsolute).join('/');
3959
3960   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3961 };
3962
3963 // path.normalize(path)
3964 // posix version
3965 exports.normalize = function(path) {
3966   var isAbsolute = exports.isAbsolute(path),
3967       trailingSlash = substr(path, -1) === '/';
3968
3969   // Normalize the path
3970   path = normalizeArray(filter(path.split('/'), function(p) {
3971     return !!p;
3972   }), !isAbsolute).join('/');
3973
3974   if (!path && !isAbsolute) {
3975     path = '.';
3976   }
3977   if (path && trailingSlash) {
3978     path += '/';
3979   }
3980
3981   return (isAbsolute ? '/' : '') + path;
3982 };
3983
3984 // posix version
3985 exports.isAbsolute = function(path) {
3986   return path.charAt(0) === '/';
3987 };
3988
3989 // posix version
3990 exports.join = function() {
3991   var paths = Array.prototype.slice.call(arguments, 0);
3992   return exports.normalize(filter(paths, function(p, index) {
3993     if (typeof p !== 'string') {
3994       throw new TypeError('Arguments to path.join must be strings');
3995     }
3996     return p;
3997   }).join('/'));
3998 };
3999
4000
4001 // path.relative(from, to)
4002 // posix version
4003 exports.relative = function(from, to) {
4004   from = exports.resolve(from).substr(1);
4005   to = exports.resolve(to).substr(1);
4006
4007   function trim(arr) {
4008     var start = 0;
4009     for (; start < arr.length; start++) {
4010       if (arr[start] !== '') break;
4011     }
4012
4013     var end = arr.length - 1;
4014     for (; end >= 0; end--) {
4015       if (arr[end] !== '') break;
4016     }
4017
4018     if (start > end) return [];
4019     return arr.slice(start, end - start + 1);
4020   }
4021
4022   var fromParts = trim(from.split('/'));
4023   var toParts = trim(to.split('/'));
4024
4025   var length = Math.min(fromParts.length, toParts.length);
4026   var samePartsLength = length;
4027   for (var i = 0; i < length; i++) {
4028     if (fromParts[i] !== toParts[i]) {
4029       samePartsLength = i;
4030       break;
4031     }
4032   }
4033
4034   var outputParts = [];
4035   for (var i = samePartsLength; i < fromParts.length; i++) {
4036     outputParts.push('..');
4037   }
4038
4039   outputParts = outputParts.concat(toParts.slice(samePartsLength));
4040
4041   return outputParts.join('/');
4042 };
4043
4044 exports.sep = '/';
4045 exports.delimiter = ':';
4046
4047 exports.dirname = function(path) {
4048   var result = splitPath(path),
4049       root = result[0],
4050       dir = result[1];
4051
4052   if (!root && !dir) {
4053     // No dirname whatsoever
4054     return '.';
4055   }
4056
4057   if (dir) {
4058     // It has a dirname, strip trailing slash
4059     dir = dir.substr(0, dir.length - 1);
4060   }
4061
4062   return root + dir;
4063 };
4064
4065
4066 exports.basename = function(path, ext) {
4067   var f = splitPath(path)[2];
4068   // TODO: make this comparison case-insensitive on windows?
4069   if (ext && f.substr(-1 * ext.length) === ext) {
4070     f = f.substr(0, f.length - ext.length);
4071   }
4072   return f;
4073 };
4074
4075
4076 exports.extname = function(path) {
4077   return splitPath(path)[3];
4078 };
4079
4080 function filter (xs, f) {
4081     if (xs.filter) return xs.filter(f);
4082     var res = [];
4083     for (var i = 0; i < xs.length; i++) {
4084         if (f(xs[i], i, xs)) res.push(xs[i]);
4085     }
4086     return res;
4087 }
4088
4089 // String.prototype.substr - negative index don't work in IE8
4090 var substr = 'ab'.substr(-1) === 'b'
4091     ? function (str, start, len) { return str.substr(start, len) }
4092     : function (str, start, len) {
4093         if (start < 0) start = str.length + start;
4094         return str.substr(start, len);
4095     }
4096 ;
4097
4098 }).call(this,require('_process'))
4099
4100 },{"_process":6}],23:[function(require,module,exports){
4101 'use strict';
4102
4103 module.exports = Pbf;
4104
4105 var ieee754 = require('ieee754');
4106
4107 function Pbf(buf) {
4108     this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4109     this.pos = 0;
4110     this.type = 0;
4111     this.length = this.buf.length;
4112 }
4113
4114 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4115 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4116 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4117 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4118
4119 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4120     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4121
4122 Pbf.prototype = {
4123
4124     destroy: function() {
4125         this.buf = null;
4126     },
4127
4128     // === READING =================================================================
4129
4130     readFields: function(readField, result, end) {
4131         end = end || this.length;
4132
4133         while (this.pos < end) {
4134             var val = this.readVarint(),
4135                 tag = val >> 3,
4136                 startPos = this.pos;
4137
4138             this.type = val & 0x7;
4139             readField(tag, result, this);
4140
4141             if (this.pos === startPos) this.skip(val);
4142         }
4143         return result;
4144     },
4145
4146     readMessage: function(readField, result) {
4147         return this.readFields(readField, result, this.readVarint() + this.pos);
4148     },
4149
4150     readFixed32: function() {
4151         var val = readUInt32(this.buf, this.pos);
4152         this.pos += 4;
4153         return val;
4154     },
4155
4156     readSFixed32: function() {
4157         var val = readInt32(this.buf, this.pos);
4158         this.pos += 4;
4159         return val;
4160     },
4161
4162     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4163
4164     readFixed64: function() {
4165         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4166         this.pos += 8;
4167         return val;
4168     },
4169
4170     readSFixed64: function() {
4171         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4172         this.pos += 8;
4173         return val;
4174     },
4175
4176     readFloat: function() {
4177         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4178         this.pos += 4;
4179         return val;
4180     },
4181
4182     readDouble: function() {
4183         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4184         this.pos += 8;
4185         return val;
4186     },
4187
4188     readVarint: function(isSigned) {
4189         var buf = this.buf,
4190             val, b;
4191
4192         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
4193         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
4194         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4195         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4196         b = buf[this.pos];   val |= (b & 0x0f) << 28;
4197
4198         return readVarintRemainder(val, isSigned, this);
4199     },
4200
4201     readVarint64: function() { // for compatibility with v2.0.1
4202         return this.readVarint(true);
4203     },
4204
4205     readSVarint: function() {
4206         var num = this.readVarint();
4207         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4208     },
4209
4210     readBoolean: function() {
4211         return Boolean(this.readVarint());
4212     },
4213
4214     readString: function() {
4215         var end = this.readVarint() + this.pos,
4216             str = readUtf8(this.buf, this.pos, end);
4217         this.pos = end;
4218         return str;
4219     },
4220
4221     readBytes: function() {
4222         var end = this.readVarint() + this.pos,
4223             buffer = this.buf.subarray(this.pos, end);
4224         this.pos = end;
4225         return buffer;
4226     },
4227
4228     // verbose for performance reasons; doesn't affect gzipped size
4229
4230     readPackedVarint: function(arr, isSigned) {
4231         var end = readPackedEnd(this);
4232         arr = arr || [];
4233         while (this.pos < end) arr.push(this.readVarint(isSigned));
4234         return arr;
4235     },
4236     readPackedSVarint: function(arr) {
4237         var end = readPackedEnd(this);
4238         arr = arr || [];
4239         while (this.pos < end) arr.push(this.readSVarint());
4240         return arr;
4241     },
4242     readPackedBoolean: function(arr) {
4243         var end = readPackedEnd(this);
4244         arr = arr || [];
4245         while (this.pos < end) arr.push(this.readBoolean());
4246         return arr;
4247     },
4248     readPackedFloat: function(arr) {
4249         var end = readPackedEnd(this);
4250         arr = arr || [];
4251         while (this.pos < end) arr.push(this.readFloat());
4252         return arr;
4253     },
4254     readPackedDouble: function(arr) {
4255         var end = readPackedEnd(this);
4256         arr = arr || [];
4257         while (this.pos < end) arr.push(this.readDouble());
4258         return arr;
4259     },
4260     readPackedFixed32: function(arr) {
4261         var end = readPackedEnd(this);
4262         arr = arr || [];
4263         while (this.pos < end) arr.push(this.readFixed32());
4264         return arr;
4265     },
4266     readPackedSFixed32: function(arr) {
4267         var end = readPackedEnd(this);
4268         arr = arr || [];
4269         while (this.pos < end) arr.push(this.readSFixed32());
4270         return arr;
4271     },
4272     readPackedFixed64: function(arr) {
4273         var end = readPackedEnd(this);
4274         arr = arr || [];
4275         while (this.pos < end) arr.push(this.readFixed64());
4276         return arr;
4277     },
4278     readPackedSFixed64: function(arr) {
4279         var end = readPackedEnd(this);
4280         arr = arr || [];
4281         while (this.pos < end) arr.push(this.readSFixed64());
4282         return arr;
4283     },
4284
4285     skip: function(val) {
4286         var type = val & 0x7;
4287         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4288         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4289         else if (type === Pbf.Fixed32) this.pos += 4;
4290         else if (type === Pbf.Fixed64) this.pos += 8;
4291         else throw new Error('Unimplemented type: ' + type);
4292     },
4293
4294     // === WRITING =================================================================
4295
4296     writeTag: function(tag, type) {
4297         this.writeVarint((tag << 3) | type);
4298     },
4299
4300     realloc: function(min) {
4301         var length = this.length || 16;
4302
4303         while (length < this.pos + min) length *= 2;
4304
4305         if (length !== this.length) {
4306             var buf = new Uint8Array(length);
4307             buf.set(this.buf);
4308             this.buf = buf;
4309             this.length = length;
4310         }
4311     },
4312
4313     finish: function() {
4314         this.length = this.pos;
4315         this.pos = 0;
4316         return this.buf.subarray(0, this.length);
4317     },
4318
4319     writeFixed32: function(val) {
4320         this.realloc(4);
4321         writeInt32(this.buf, val, this.pos);
4322         this.pos += 4;
4323     },
4324
4325     writeSFixed32: function(val) {
4326         this.realloc(4);
4327         writeInt32(this.buf, val, this.pos);
4328         this.pos += 4;
4329     },
4330
4331     writeFixed64: function(val) {
4332         this.realloc(8);
4333         writeInt32(this.buf, val & -1, this.pos);
4334         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4335         this.pos += 8;
4336     },
4337
4338     writeSFixed64: function(val) {
4339         this.realloc(8);
4340         writeInt32(this.buf, val & -1, this.pos);
4341         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4342         this.pos += 8;
4343     },
4344
4345     writeVarint: function(val) {
4346         val = +val || 0;
4347
4348         if (val > 0xfffffff || val < 0) {
4349             writeBigVarint(val, this);
4350             return;
4351         }
4352
4353         this.realloc(4);
4354
4355         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4356         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4357         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
4359     },
4360
4361     writeSVarint: function(val) {
4362         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4363     },
4364
4365     writeBoolean: function(val) {
4366         this.writeVarint(Boolean(val));
4367     },
4368
4369     writeString: function(str) {
4370         str = String(str);
4371         this.realloc(str.length * 4);
4372
4373         this.pos++; // reserve 1 byte for short string length
4374
4375         var startPos = this.pos;
4376         // write the string directly to the buffer and see how much was written
4377         this.pos = writeUtf8(this.buf, str, this.pos);
4378         var len = this.pos - startPos;
4379
4380         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4381
4382         // finally, write the message length in the reserved place and restore the position
4383         this.pos = startPos - 1;
4384         this.writeVarint(len);
4385         this.pos += len;
4386     },
4387
4388     writeFloat: function(val) {
4389         this.realloc(4);
4390         ieee754.write(this.buf, val, this.pos, true, 23, 4);
4391         this.pos += 4;
4392     },
4393
4394     writeDouble: function(val) {
4395         this.realloc(8);
4396         ieee754.write(this.buf, val, this.pos, true, 52, 8);
4397         this.pos += 8;
4398     },
4399
4400     writeBytes: function(buffer) {
4401         var len = buffer.length;
4402         this.writeVarint(len);
4403         this.realloc(len);
4404         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4405     },
4406
4407     writeRawMessage: function(fn, obj) {
4408         this.pos++; // reserve 1 byte for short message length
4409
4410         // write the message directly to the buffer and see how much was written
4411         var startPos = this.pos;
4412         fn(obj, this);
4413         var len = this.pos - startPos;
4414
4415         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4416
4417         // finally, write the message length in the reserved place and restore the position
4418         this.pos = startPos - 1;
4419         this.writeVarint(len);
4420         this.pos += len;
4421     },
4422
4423     writeMessage: function(tag, fn, obj) {
4424         this.writeTag(tag, Pbf.Bytes);
4425         this.writeRawMessage(fn, obj);
4426     },
4427
4428     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
4429     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
4430     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
4431     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
4432     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
4433     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
4434     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4435     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
4436     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4437
4438     writeBytesField: function(tag, buffer) {
4439         this.writeTag(tag, Pbf.Bytes);
4440         this.writeBytes(buffer);
4441     },
4442     writeFixed32Field: function(tag, val) {
4443         this.writeTag(tag, Pbf.Fixed32);
4444         this.writeFixed32(val);
4445     },
4446     writeSFixed32Field: function(tag, val) {
4447         this.writeTag(tag, Pbf.Fixed32);
4448         this.writeSFixed32(val);
4449     },
4450     writeFixed64Field: function(tag, val) {
4451         this.writeTag(tag, Pbf.Fixed64);
4452         this.writeFixed64(val);
4453     },
4454     writeSFixed64Field: function(tag, val) {
4455         this.writeTag(tag, Pbf.Fixed64);
4456         this.writeSFixed64(val);
4457     },
4458     writeVarintField: function(tag, val) {
4459         this.writeTag(tag, Pbf.Varint);
4460         this.writeVarint(val);
4461     },
4462     writeSVarintField: function(tag, val) {
4463         this.writeTag(tag, Pbf.Varint);
4464         this.writeSVarint(val);
4465     },
4466     writeStringField: function(tag, str) {
4467         this.writeTag(tag, Pbf.Bytes);
4468         this.writeString(str);
4469     },
4470     writeFloatField: function(tag, val) {
4471         this.writeTag(tag, Pbf.Fixed32);
4472         this.writeFloat(val);
4473     },
4474     writeDoubleField: function(tag, val) {
4475         this.writeTag(tag, Pbf.Fixed64);
4476         this.writeDouble(val);
4477     },
4478     writeBooleanField: function(tag, val) {
4479         this.writeVarintField(tag, Boolean(val));
4480     }
4481 };
4482
4483 function readVarintRemainder(l, s, p) {
4484     var buf = p.buf,
4485         h, b;
4486
4487     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
4488     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
4489     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4490     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4491     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4492     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4493
4494     throw new Error('Expected varint not more than 10 bytes');
4495 }
4496
4497 function readPackedEnd(pbf) {
4498     return pbf.type === Pbf.Bytes ?
4499         pbf.readVarint() + pbf.pos : pbf.pos + 1;
4500 }
4501
4502 function toNum(low, high, isSigned) {
4503     if (isSigned) {
4504         return high * 0x100000000 + (low >>> 0);
4505     }
4506
4507     return ((high >>> 0) * 0x100000000) + (low >>> 0);
4508 }
4509
4510 function writeBigVarint(val, pbf) {
4511     var low, high;
4512
4513     if (val >= 0) {
4514         low  = (val % 0x100000000) | 0;
4515         high = (val / 0x100000000) | 0;
4516     } else {
4517         low  = ~(-val % 0x100000000);
4518         high = ~(-val / 0x100000000);
4519
4520         if (low ^ 0xffffffff) {
4521             low = (low + 1) | 0;
4522         } else {
4523             low = 0;
4524             high = (high + 1) | 0;
4525         }
4526     }
4527
4528     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4529         throw new Error('Given varint doesn\'t fit into 10 bytes');
4530     }
4531
4532     pbf.realloc(10);
4533
4534     writeBigVarintLow(low, high, pbf);
4535     writeBigVarintHigh(high, pbf);
4536 }
4537
4538 function writeBigVarintLow(low, high, pbf) {
4539     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4540     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4541     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4542     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4543     pbf.buf[pbf.pos]   = low & 0x7f;
4544 }
4545
4546 function writeBigVarintHigh(high, pbf) {
4547     var lsb = (high & 0x07) << 4;
4548
4549     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4550     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4551     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4552     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4553     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4554     pbf.buf[pbf.pos++]  = high & 0x7f;
4555 }
4556
4557 function makeRoomForExtraLength(startPos, len, pbf) {
4558     var extraLen =
4559         len <= 0x3fff ? 1 :
4560         len <= 0x1fffff ? 2 :
4561         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4562
4563     // if 1 byte isn't enough for encoding message length, shift the data to the right
4564     pbf.realloc(extraLen);
4565     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4566 }
4567
4568 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
4569 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
4570 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
4571 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
4572 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
4573 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
4574 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4575 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
4576 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4577
4578 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4579
4580 function readUInt32(buf, pos) {
4581     return ((buf[pos]) |
4582         (buf[pos + 1] << 8) |
4583         (buf[pos + 2] << 16)) +
4584         (buf[pos + 3] * 0x1000000);
4585 }
4586
4587 function writeInt32(buf, val, pos) {
4588     buf[pos] = val;
4589     buf[pos + 1] = (val >>> 8);
4590     buf[pos + 2] = (val >>> 16);
4591     buf[pos + 3] = (val >>> 24);
4592 }
4593
4594 function readInt32(buf, pos) {
4595     return ((buf[pos]) |
4596         (buf[pos + 1] << 8) |
4597         (buf[pos + 2] << 16)) +
4598         (buf[pos + 3] << 24);
4599 }
4600
4601 function readUtf8(buf, pos, end) {
4602     var str = '';
4603     var i = pos;
4604
4605     while (i < end) {
4606         var b0 = buf[i];
4607         var c = null; // codepoint
4608         var bytesPerSequence =
4609             b0 > 0xEF ? 4 :
4610             b0 > 0xDF ? 3 :
4611             b0 > 0xBF ? 2 : 1;
4612
4613         if (i + bytesPerSequence > end) break;
4614
4615         var b1, b2, b3;
4616
4617         if (bytesPerSequence === 1) {
4618             if (b0 < 0x80) {
4619                 c = b0;
4620             }
4621         } else if (bytesPerSequence === 2) {
4622             b1 = buf[i + 1];
4623             if ((b1 & 0xC0) === 0x80) {
4624                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4625                 if (c <= 0x7F) {
4626                     c = null;
4627                 }
4628             }
4629         } else if (bytesPerSequence === 3) {
4630             b1 = buf[i + 1];
4631             b2 = buf[i + 2];
4632             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4633                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4634                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4635                     c = null;
4636                 }
4637             }
4638         } else if (bytesPerSequence === 4) {
4639             b1 = buf[i + 1];
4640             b2 = buf[i + 2];
4641             b3 = buf[i + 3];
4642             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4643                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4644                 if (c <= 0xFFFF || c >= 0x110000) {
4645                     c = null;
4646                 }
4647             }
4648         }
4649
4650         if (c === null) {
4651             c = 0xFFFD;
4652             bytesPerSequence = 1;
4653
4654         } else if (c > 0xFFFF) {
4655             c -= 0x10000;
4656             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4657             c = 0xDC00 | c & 0x3FF;
4658         }
4659
4660         str += String.fromCharCode(c);
4661         i += bytesPerSequence;
4662     }
4663
4664     return str;
4665 }
4666
4667 function writeUtf8(buf, str, pos) {
4668     for (var i = 0, c, lead; i < str.length; i++) {
4669         c = str.charCodeAt(i); // code point
4670
4671         if (c > 0xD7FF && c < 0xE000) {
4672             if (lead) {
4673                 if (c < 0xDC00) {
4674                     buf[pos++] = 0xEF;
4675                     buf[pos++] = 0xBF;
4676                     buf[pos++] = 0xBD;
4677                     lead = c;
4678                     continue;
4679                 } else {
4680                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4681                     lead = null;
4682                 }
4683             } else {
4684                 if (c > 0xDBFF || (i + 1 === str.length)) {
4685                     buf[pos++] = 0xEF;
4686                     buf[pos++] = 0xBF;
4687                     buf[pos++] = 0xBD;
4688                 } else {
4689                     lead = c;
4690                 }
4691                 continue;
4692             }
4693         } else if (lead) {
4694             buf[pos++] = 0xEF;
4695             buf[pos++] = 0xBF;
4696             buf[pos++] = 0xBD;
4697             lead = null;
4698         }
4699
4700         if (c < 0x80) {
4701             buf[pos++] = c;
4702         } else {
4703             if (c < 0x800) {
4704                 buf[pos++] = c >> 0x6 | 0xC0;
4705             } else {
4706                 if (c < 0x10000) {
4707                     buf[pos++] = c >> 0xC | 0xE0;
4708                 } else {
4709                     buf[pos++] = c >> 0x12 | 0xF0;
4710                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
4711                 }
4712                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4713             }
4714             buf[pos++] = c & 0x3F | 0x80;
4715         }
4716     }
4717     return pos;
4718 }
4719
4720 },{"ieee754":17}],24:[function(require,module,exports){
4721 'use strict';
4722
4723 module.exports = partialSort;
4724
4725 // Floyd-Rivest selection algorithm:
4726 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4727 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4728
4729 function partialSort(arr, k, left, right, compare) {
4730     left = left || 0;
4731     right = right || (arr.length - 1);
4732     compare = compare || defaultCompare;
4733
4734     while (right > left) {
4735         if (right - left > 600) {
4736             var n = right - left + 1;
4737             var m = k - left + 1;
4738             var z = Math.log(n);
4739             var s = 0.5 * Math.exp(2 * z / 3);
4740             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4741             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4742             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4743             partialSort(arr, k, newLeft, newRight, compare);
4744         }
4745
4746         var t = arr[k];
4747         var i = left;
4748         var j = right;
4749
4750         swap(arr, left, k);
4751         if (compare(arr[right], t) > 0) swap(arr, left, right);
4752
4753         while (i < j) {
4754             swap(arr, i, j);
4755             i++;
4756             j--;
4757             while (compare(arr[i], t) < 0) i++;
4758             while (compare(arr[j], t) > 0) j--;
4759         }
4760
4761         if (compare(arr[left], t) === 0) swap(arr, left, j);
4762         else {
4763             j++;
4764             swap(arr, j, right);
4765         }
4766
4767         if (j <= k) left = j + 1;
4768         if (k <= j) right = j - 1;
4769     }
4770 }
4771
4772 function swap(arr, i, j) {
4773     var tmp = arr[i];
4774     arr[i] = arr[j];
4775     arr[j] = tmp;
4776 }
4777
4778 function defaultCompare(a, b) {
4779     return a < b ? -1 : a > b ? 1 : 0;
4780 }
4781
4782 },{}],25:[function(require,module,exports){
4783 'use strict';
4784
4785 module.exports = rbush;
4786
4787 var quickselect = require('quickselect');
4788
4789 function rbush(maxEntries, format) {
4790     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4791
4792     // max entries in a node is 9 by default; min node fill is 40% for best performance
4793     this._maxEntries = Math.max(4, maxEntries || 9);
4794     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4795
4796     if (format) {
4797         this._initFormat(format);
4798     }
4799
4800     this.clear();
4801 }
4802
4803 rbush.prototype = {
4804
4805     all: function () {
4806         return this._all(this.data, []);
4807     },
4808
4809     search: function (bbox) {
4810
4811         var node = this.data,
4812             result = [],
4813             toBBox = this.toBBox;
4814
4815         if (!intersects(bbox, node)) return result;
4816
4817         var nodesToSearch = [],
4818             i, len, child, childBBox;
4819
4820         while (node) {
4821             for (i = 0, len = node.children.length; i < len; i++) {
4822
4823                 child = node.children[i];
4824                 childBBox = node.leaf ? toBBox(child) : child;
4825
4826                 if (intersects(bbox, childBBox)) {
4827                     if (node.leaf) result.push(child);
4828                     else if (contains(bbox, childBBox)) this._all(child, result);
4829                     else nodesToSearch.push(child);
4830                 }
4831             }
4832             node = nodesToSearch.pop();
4833         }
4834
4835         return result;
4836     },
4837
4838     collides: function (bbox) {
4839
4840         var node = this.data,
4841             toBBox = this.toBBox;
4842
4843         if (!intersects(bbox, node)) return false;
4844
4845         var nodesToSearch = [],
4846             i, len, child, childBBox;
4847
4848         while (node) {
4849             for (i = 0, len = node.children.length; i < len; i++) {
4850
4851                 child = node.children[i];
4852                 childBBox = node.leaf ? toBBox(child) : child;
4853
4854                 if (intersects(bbox, childBBox)) {
4855                     if (node.leaf || contains(bbox, childBBox)) return true;
4856                     nodesToSearch.push(child);
4857                 }
4858             }
4859             node = nodesToSearch.pop();
4860         }
4861
4862         return false;
4863     },
4864
4865     load: function (data) {
4866         if (!(data && data.length)) return this;
4867
4868         if (data.length < this._minEntries) {
4869             for (var i = 0, len = data.length; i < len; i++) {
4870                 this.insert(data[i]);
4871             }
4872             return this;
4873         }
4874
4875         // recursively build the tree with the given data from stratch using OMT algorithm
4876         var node = this._build(data.slice(), 0, data.length - 1, 0);
4877
4878         if (!this.data.children.length) {
4879             // save as is if tree is empty
4880             this.data = node;
4881
4882         } else if (this.data.height === node.height) {
4883             // split root if trees have the same height
4884             this._splitRoot(this.data, node);
4885
4886         } else {
4887             if (this.data.height < node.height) {
4888                 // swap trees if inserted one is bigger
4889                 var tmpNode = this.data;
4890                 this.data = node;
4891                 node = tmpNode;
4892             }
4893
4894             // insert the small tree into the large tree at appropriate level
4895             this._insert(node, this.data.height - node.height - 1, true);
4896         }
4897
4898         return this;
4899     },
4900
4901     insert: function (item) {
4902         if (item) this._insert(item, this.data.height - 1);
4903         return this;
4904     },
4905
4906     clear: function () {
4907         this.data = createNode([]);
4908         return this;
4909     },
4910
4911     remove: function (item, equalsFn) {
4912         if (!item) return this;
4913
4914         var node = this.data,
4915             bbox = this.toBBox(item),
4916             path = [],
4917             indexes = [],
4918             i, parent, index, goingUp;
4919
4920         // depth-first iterative tree traversal
4921         while (node || path.length) {
4922
4923             if (!node) { // go up
4924                 node = path.pop();
4925                 parent = path[path.length - 1];
4926                 i = indexes.pop();
4927                 goingUp = true;
4928             }
4929
4930             if (node.leaf) { // check current node
4931                 index = findItem(item, node.children, equalsFn);
4932
4933                 if (index !== -1) {
4934                     // item found, remove the item and condense tree upwards
4935                     node.children.splice(index, 1);
4936                     path.push(node);
4937                     this._condense(path);
4938                     return this;
4939                 }
4940             }
4941
4942             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4943                 path.push(node);
4944                 indexes.push(i);
4945                 i = 0;
4946                 parent = node;
4947                 node = node.children[0];
4948
4949             } else if (parent) { // go right
4950                 i++;
4951                 node = parent.children[i];
4952                 goingUp = false;
4953
4954             } else node = null; // nothing found
4955         }
4956
4957         return this;
4958     },
4959
4960     toBBox: function (item) { return item; },
4961
4962     compareMinX: compareNodeMinX,
4963     compareMinY: compareNodeMinY,
4964
4965     toJSON: function () { return this.data; },
4966
4967     fromJSON: function (data) {
4968         this.data = data;
4969         return this;
4970     },
4971
4972     _all: function (node, result) {
4973         var nodesToSearch = [];
4974         while (node) {
4975             if (node.leaf) result.push.apply(result, node.children);
4976             else nodesToSearch.push.apply(nodesToSearch, node.children);
4977
4978             node = nodesToSearch.pop();
4979         }
4980         return result;
4981     },
4982
4983     _build: function (items, left, right, height) {
4984
4985         var N = right - left + 1,
4986             M = this._maxEntries,
4987             node;
4988
4989         if (N <= M) {
4990             // reached leaf level; return leaf
4991             node = createNode(items.slice(left, right + 1));
4992             calcBBox(node, this.toBBox);
4993             return node;
4994         }
4995
4996         if (!height) {
4997             // target height of the bulk-loaded tree
4998             height = Math.ceil(Math.log(N) / Math.log(M));
4999
5000             // target number of root entries to maximize storage utilization
5001             M = Math.ceil(N / Math.pow(M, height - 1));
5002         }
5003
5004         node = createNode([]);
5005         node.leaf = false;
5006         node.height = height;
5007
5008         // split the items into M mostly square tiles
5009
5010         var N2 = Math.ceil(N / M),
5011             N1 = N2 * Math.ceil(Math.sqrt(M)),
5012             i, j, right2, right3;
5013
5014         multiSelect(items, left, right, N1, this.compareMinX);
5015
5016         for (i = left; i <= right; i += N1) {
5017
5018             right2 = Math.min(i + N1 - 1, right);
5019
5020             multiSelect(items, i, right2, N2, this.compareMinY);
5021
5022             for (j = i; j <= right2; j += N2) {
5023
5024                 right3 = Math.min(j + N2 - 1, right2);
5025
5026                 // pack each entry recursively
5027                 node.children.push(this._build(items, j, right3, height - 1));
5028             }
5029         }
5030
5031         calcBBox(node, this.toBBox);
5032
5033         return node;
5034     },
5035
5036     _chooseSubtree: function (bbox, node, level, path) {
5037
5038         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5039
5040         while (true) {
5041             path.push(node);
5042
5043             if (node.leaf || path.length - 1 === level) break;
5044
5045             minArea = minEnlargement = Infinity;
5046
5047             for (i = 0, len = node.children.length; i < len; i++) {
5048                 child = node.children[i];
5049                 area = bboxArea(child);
5050                 enlargement = enlargedArea(bbox, child) - area;
5051
5052                 // choose entry with the least area enlargement
5053                 if (enlargement < minEnlargement) {
5054                     minEnlargement = enlargement;
5055                     minArea = area < minArea ? area : minArea;
5056                     targetNode = child;
5057
5058                 } else if (enlargement === minEnlargement) {
5059                     // otherwise choose one with the smallest area
5060                     if (area < minArea) {
5061                         minArea = area;
5062                         targetNode = child;
5063                     }
5064                 }
5065             }
5066
5067             node = targetNode || node.children[0];
5068         }
5069
5070         return node;
5071     },
5072
5073     _insert: function (item, level, isNode) {
5074
5075         var toBBox = this.toBBox,
5076             bbox = isNode ? item : toBBox(item),
5077             insertPath = [];
5078
5079         // find the best node for accommodating the item, saving all nodes along the path too
5080         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5081
5082         // put the item into the node
5083         node.children.push(item);
5084         extend(node, bbox);
5085
5086         // split on node overflow; propagate upwards if necessary
5087         while (level >= 0) {
5088             if (insertPath[level].children.length > this._maxEntries) {
5089                 this._split(insertPath, level);
5090                 level--;
5091             } else break;
5092         }
5093
5094         // adjust bboxes along the insertion path
5095         this._adjustParentBBoxes(bbox, insertPath, level);
5096     },
5097
5098     // split overflowed node into two
5099     _split: function (insertPath, level) {
5100
5101         var node = insertPath[level],
5102             M = node.children.length,
5103             m = this._minEntries;
5104
5105         this._chooseSplitAxis(node, m, M);
5106
5107         var splitIndex = this._chooseSplitIndex(node, m, M);
5108
5109         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5110         newNode.height = node.height;
5111         newNode.leaf = node.leaf;
5112
5113         calcBBox(node, this.toBBox);
5114         calcBBox(newNode, this.toBBox);
5115
5116         if (level) insertPath[level - 1].children.push(newNode);
5117         else this._splitRoot(node, newNode);
5118     },
5119
5120     _splitRoot: function (node, newNode) {
5121         // split root node
5122         this.data = createNode([node, newNode]);
5123         this.data.height = node.height + 1;
5124         this.data.leaf = false;
5125         calcBBox(this.data, this.toBBox);
5126     },
5127
5128     _chooseSplitIndex: function (node, m, M) {
5129
5130         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5131
5132         minOverlap = minArea = Infinity;
5133
5134         for (i = m; i <= M - m; i++) {
5135             bbox1 = distBBox(node, 0, i, this.toBBox);
5136             bbox2 = distBBox(node, i, M, this.toBBox);
5137
5138             overlap = intersectionArea(bbox1, bbox2);
5139             area = bboxArea(bbox1) + bboxArea(bbox2);
5140
5141             // choose distribution with minimum overlap
5142             if (overlap < minOverlap) {
5143                 minOverlap = overlap;
5144                 index = i;
5145
5146                 minArea = area < minArea ? area : minArea;
5147
5148             } else if (overlap === minOverlap) {
5149                 // otherwise choose distribution with minimum area
5150                 if (area < minArea) {
5151                     minArea = area;
5152                     index = i;
5153                 }
5154             }
5155         }
5156
5157         return index;
5158     },
5159
5160     // sorts node children by the best axis for split
5161     _chooseSplitAxis: function (node, m, M) {
5162
5163         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5164             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5165             xMargin = this._allDistMargin(node, m, M, compareMinX),
5166             yMargin = this._allDistMargin(node, m, M, compareMinY);
5167
5168         // if total distributions margin value is minimal for x, sort by minX,
5169         // otherwise it's already sorted by minY
5170         if (xMargin < yMargin) node.children.sort(compareMinX);
5171     },
5172
5173     // total margin of all possible split distributions where each node is at least m full
5174     _allDistMargin: function (node, m, M, compare) {
5175
5176         node.children.sort(compare);
5177
5178         var toBBox = this.toBBox,
5179             leftBBox = distBBox(node, 0, m, toBBox),
5180             rightBBox = distBBox(node, M - m, M, toBBox),
5181             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5182             i, child;
5183
5184         for (i = m; i < M - m; i++) {
5185             child = node.children[i];
5186             extend(leftBBox, node.leaf ? toBBox(child) : child);
5187             margin += bboxMargin(leftBBox);
5188         }
5189
5190         for (i = M - m - 1; i >= m; i--) {
5191             child = node.children[i];
5192             extend(rightBBox, node.leaf ? toBBox(child) : child);
5193             margin += bboxMargin(rightBBox);
5194         }
5195
5196         return margin;
5197     },
5198
5199     _adjustParentBBoxes: function (bbox, path, level) {
5200         // adjust bboxes along the given tree path
5201         for (var i = level; i >= 0; i--) {
5202             extend(path[i], bbox);
5203         }
5204     },
5205
5206     _condense: function (path) {
5207         // go through the path, removing empty nodes and updating bboxes
5208         for (var i = path.length - 1, siblings; i >= 0; i--) {
5209             if (path[i].children.length === 0) {
5210                 if (i > 0) {
5211                     siblings = path[i - 1].children;
5212                     siblings.splice(siblings.indexOf(path[i]), 1);
5213
5214                 } else this.clear();
5215
5216             } else calcBBox(path[i], this.toBBox);
5217         }
5218     },
5219
5220     _initFormat: function (format) {
5221         // data format (minX, minY, maxX, maxY accessors)
5222
5223         // uses eval-type function compilation instead of just accepting a toBBox function
5224         // because the algorithms are very sensitive to sorting functions performance,
5225         // so they should be dead simple and without inner calls
5226
5227         var compareArr = ['return a', ' - b', ';'];
5228
5229         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5230         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5231
5232         this.toBBox = new Function('a',
5233             'return {minX: a' + format[0] +
5234             ', minY: a' + format[1] +
5235             ', maxX: a' + format[2] +
5236             ', maxY: a' + format[3] + '};');
5237     }
5238 };
5239
5240 function findItem(item, items, equalsFn) {
5241     if (!equalsFn) return items.indexOf(item);
5242
5243     for (var i = 0; i < items.length; i++) {
5244         if (equalsFn(item, items[i])) return i;
5245     }
5246     return -1;
5247 }
5248
5249 // calculate node's bbox from bboxes of its children
5250 function calcBBox(node, toBBox) {
5251     distBBox(node, 0, node.children.length, toBBox, node);
5252 }
5253
5254 // min bounding rectangle of node children from k to p-1
5255 function distBBox(node, k, p, toBBox, destNode) {
5256     if (!destNode) destNode = createNode(null);
5257     destNode.minX = Infinity;
5258     destNode.minY = Infinity;
5259     destNode.maxX = -Infinity;
5260     destNode.maxY = -Infinity;
5261
5262     for (var i = k, child; i < p; i++) {
5263         child = node.children[i];
5264         extend(destNode, node.leaf ? toBBox(child) : child);
5265     }
5266
5267     return destNode;
5268 }
5269
5270 function extend(a, b) {
5271     a.minX = Math.min(a.minX, b.minX);
5272     a.minY = Math.min(a.minY, b.minY);
5273     a.maxX = Math.max(a.maxX, b.maxX);
5274     a.maxY = Math.max(a.maxY, b.maxY);
5275     return a;
5276 }
5277
5278 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5279 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5280
5281 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5282 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5283
5284 function enlargedArea(a, b) {
5285     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5286            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5287 }
5288
5289 function intersectionArea(a, b) {
5290     var minX = Math.max(a.minX, b.minX),
5291         minY = Math.max(a.minY, b.minY),
5292         maxX = Math.min(a.maxX, b.maxX),
5293         maxY = Math.min(a.maxY, b.maxY);
5294
5295     return Math.max(0, maxX - minX) *
5296            Math.max(0, maxY - minY);
5297 }
5298
5299 function contains(a, b) {
5300     return a.minX <= b.minX &&
5301            a.minY <= b.minY &&
5302            b.maxX <= a.maxX &&
5303            b.maxY <= a.maxY;
5304 }
5305
5306 function intersects(a, b) {
5307     return b.minX <= a.maxX &&
5308            b.minY <= a.maxY &&
5309            b.maxX >= a.minX &&
5310            b.maxY >= a.minY;
5311 }
5312
5313 function createNode(children) {
5314     return {
5315         children: children,
5316         height: 1,
5317         leaf: true,
5318         minX: Infinity,
5319         minY: Infinity,
5320         maxX: -Infinity,
5321         maxY: -Infinity
5322     };
5323 }
5324
5325 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5326 // combines selection algorithm with binary divide & conquer approach
5327
5328 function multiSelect(arr, left, right, n, compare) {
5329     var stack = [left, right],
5330         mid;
5331
5332     while (stack.length) {
5333         right = stack.pop();
5334         left = stack.pop();
5335
5336         if (right - left <= n) continue;
5337
5338         mid = left + Math.ceil((right - left) / n / 2) * n;
5339         quickselect(arr, mid, left, right, compare);
5340
5341         stack.push(left, mid, mid, right);
5342     }
5343 }
5344
5345 },{"quickselect":24}],26:[function(require,module,exports){
5346 "use strict";
5347 var __extends = (this && this.__extends) || function (d, b) {
5348     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5349     function __() { this.constructor = d; }
5350     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5351 };
5352 var Subject_1 = require('./Subject');
5353 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5354 /**
5355  * @class BehaviorSubject<T>
5356  */
5357 var BehaviorSubject = (function (_super) {
5358     __extends(BehaviorSubject, _super);
5359     function BehaviorSubject(_value) {
5360         _super.call(this);
5361         this._value = _value;
5362     }
5363     Object.defineProperty(BehaviorSubject.prototype, "value", {
5364         get: function () {
5365             return this.getValue();
5366         },
5367         enumerable: true,
5368         configurable: true
5369     });
5370     BehaviorSubject.prototype._subscribe = function (subscriber) {
5371         var subscription = _super.prototype._subscribe.call(this, subscriber);
5372         if (subscription && !subscription.closed) {
5373             subscriber.next(this._value);
5374         }
5375         return subscription;
5376     };
5377     BehaviorSubject.prototype.getValue = function () {
5378         if (this.hasError) {
5379             throw this.thrownError;
5380         }
5381         else if (this.closed) {
5382             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5383         }
5384         else {
5385             return this._value;
5386         }
5387     };
5388     BehaviorSubject.prototype.next = function (value) {
5389         _super.prototype.next.call(this, this._value = value);
5390     };
5391     return BehaviorSubject;
5392 }(Subject_1.Subject));
5393 exports.BehaviorSubject = BehaviorSubject;
5394
5395 },{"./Subject":34,"./util/ObjectUnsubscribedError":164}],27:[function(require,module,exports){
5396 "use strict";
5397 var __extends = (this && this.__extends) || function (d, b) {
5398     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5399     function __() { this.constructor = d; }
5400     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5401 };
5402 var Subscriber_1 = require('./Subscriber');
5403 /**
5404  * We need this JSDoc comment for affecting ESDoc.
5405  * @ignore
5406  * @extends {Ignored}
5407  */
5408 var InnerSubscriber = (function (_super) {
5409     __extends(InnerSubscriber, _super);
5410     function InnerSubscriber(parent, outerValue, outerIndex) {
5411         _super.call(this);
5412         this.parent = parent;
5413         this.outerValue = outerValue;
5414         this.outerIndex = outerIndex;
5415         this.index = 0;
5416     }
5417     InnerSubscriber.prototype._next = function (value) {
5418         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5419     };
5420     InnerSubscriber.prototype._error = function (error) {
5421         this.parent.notifyError(error, this);
5422         this.unsubscribe();
5423     };
5424     InnerSubscriber.prototype._complete = function () {
5425         this.parent.notifyComplete(this);
5426         this.unsubscribe();
5427     };
5428     return InnerSubscriber;
5429 }(Subscriber_1.Subscriber));
5430 exports.InnerSubscriber = InnerSubscriber;
5431
5432 },{"./Subscriber":36}],28:[function(require,module,exports){
5433 "use strict";
5434 var Observable_1 = require('./Observable');
5435 /**
5436  * Represents a push-based event or value that an {@link Observable} can emit.
5437  * This class is particularly useful for operators that manage notifications,
5438  * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5439  * others. Besides wrapping the actual delivered value, it also annotates it
5440  * with metadata of, for instance, what type of push message it is (`next`,
5441  * `error`, or `complete`).
5442  *
5443  * @see {@link materialize}
5444  * @see {@link dematerialize}
5445  * @see {@link observeOn}
5446  *
5447  * @class Notification<T>
5448  */
5449 var Notification = (function () {
5450     function Notification(kind, value, error) {
5451         this.kind = kind;
5452         this.value = value;
5453         this.error = error;
5454         this.hasValue = kind === 'N';
5455     }
5456     /**
5457      * Delivers to the given `observer` the value wrapped by this Notification.
5458      * @param {Observer} observer
5459      * @return
5460      */
5461     Notification.prototype.observe = function (observer) {
5462         switch (this.kind) {
5463             case 'N':
5464                 return observer.next && observer.next(this.value);
5465             case 'E':
5466                 return observer.error && observer.error(this.error);
5467             case 'C':
5468                 return observer.complete && observer.complete();
5469         }
5470     };
5471     /**
5472      * Given some {@link Observer} callbacks, deliver the value represented by the
5473      * current Notification to the correctly corresponding callback.
5474      * @param {function(value: T): void} next An Observer `next` callback.
5475      * @param {function(err: any): void} [error] An Observer `error` callback.
5476      * @param {function(): void} [complete] An Observer `complete` callback.
5477      * @return {any}
5478      */
5479     Notification.prototype.do = function (next, error, complete) {
5480         var kind = this.kind;
5481         switch (kind) {
5482             case 'N':
5483                 return next && next(this.value);
5484             case 'E':
5485                 return error && error(this.error);
5486             case 'C':
5487                 return complete && complete();
5488         }
5489     };
5490     /**
5491      * Takes an Observer or its individual callback functions, and calls `observe`
5492      * or `do` methods accordingly.
5493      * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5494      * the `next` callback.
5495      * @param {function(err: any): void} [error] An Observer `error` callback.
5496      * @param {function(): void} [complete] An Observer `complete` callback.
5497      * @return {any}
5498      */
5499     Notification.prototype.accept = function (nextOrObserver, error, complete) {
5500         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5501             return this.observe(nextOrObserver);
5502         }
5503         else {
5504             return this.do(nextOrObserver, error, complete);
5505         }
5506     };
5507     /**
5508      * Returns a simple Observable that just delivers the notification represented
5509      * by this Notification instance.
5510      * @return {any}
5511      */
5512     Notification.prototype.toObservable = function () {
5513         var kind = this.kind;
5514         switch (kind) {
5515             case 'N':
5516                 return Observable_1.Observable.of(this.value);
5517             case 'E':
5518                 return Observable_1.Observable.throw(this.error);
5519             case 'C':
5520                 return Observable_1.Observable.empty();
5521         }
5522         throw new Error('unexpected notification kind value');
5523     };
5524     /**
5525      * A shortcut to create a Notification instance of the type `next` from a
5526      * given value.
5527      * @param {T} value The `next` value.
5528      * @return {Notification<T>} The "next" Notification representing the
5529      * argument.
5530      */
5531     Notification.createNext = function (value) {
5532         if (typeof value !== 'undefined') {
5533             return new Notification('N', value);
5534         }
5535         return Notification.undefinedValueNotification;
5536     };
5537     /**
5538      * A shortcut to create a Notification instance of the type `error` from a
5539      * given error.
5540      * @param {any} [err] The `error` error.
5541      * @return {Notification<T>} The "error" Notification representing the
5542      * argument.
5543      */
5544     Notification.createError = function (err) {
5545         return new Notification('E', undefined, err);
5546     };
5547     /**
5548      * A shortcut to create a Notification instance of the type `complete`.
5549      * @return {Notification<any>} The valueless "complete" Notification.
5550      */
5551     Notification.createComplete = function () {
5552         return Notification.completeNotification;
5553     };
5554     Notification.completeNotification = new Notification('C');
5555     Notification.undefinedValueNotification = new Notification('N', undefined);
5556     return Notification;
5557 }());
5558 exports.Notification = Notification;
5559
5560 },{"./Observable":29}],29:[function(require,module,exports){
5561 "use strict";
5562 var root_1 = require('./util/root');
5563 var toSubscriber_1 = require('./util/toSubscriber');
5564 var observable_1 = require('./symbol/observable');
5565 /**
5566  * A representation of any set of values over any amount of time. This the most basic building block
5567  * of RxJS.
5568  *
5569  * @class Observable<T>
5570  */
5571 var Observable = (function () {
5572     /**
5573      * @constructor
5574      * @param {Function} subscribe the function that is  called when the Observable is
5575      * initially subscribed to. This function is given a Subscriber, to which new values
5576      * can be `next`ed, or an `error` method can be called to raise an error, or
5577      * `complete` can be called to notify of a successful completion.
5578      */
5579     function Observable(subscribe) {
5580         this._isScalar = false;
5581         if (subscribe) {
5582             this._subscribe = subscribe;
5583         }
5584     }
5585     /**
5586      * Creates a new Observable, with this Observable as the source, and the passed
5587      * operator defined as the new observable's operator.
5588      * @method lift
5589      * @param {Operator} operator the operator defining the operation to take on the observable
5590      * @return {Observable} a new observable with the Operator applied
5591      */
5592     Observable.prototype.lift = function (operator) {
5593         var observable = new Observable();
5594         observable.source = this;
5595         observable.operator = operator;
5596         return observable;
5597     };
5598     /**
5599      * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5600      *
5601      * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5602      *
5603      * `subscribe` is not a regular operator, but a method that calls Observables internal `subscribe` function. It
5604      * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5605      * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5606      * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5607      * thought.
5608      *
5609      * Apart from starting the execution of an Observable, this method allows you to listen for values
5610      * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5611      * following ways.
5612      *
5613      * The first way is creating an object that implements {@link Observer} interface. It should have methods
5614      * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5615      * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5616      * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5617      * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5618      * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5619      * be left uncaught.
5620      *
5621      * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5622      * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5623      * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5624      * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5625      * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5626      * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5627      *
5628      * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5629      * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5630      * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5631      * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5632      *
5633      * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5634      * It is an Observable itself that decides when these functions will be called. For example {@link of}
5635      * by default emits all its values synchronously. Always check documentation for how given Observable
5636      * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5637      *
5638      * @example <caption>Subscribe with an Observer</caption>
5639      * const sumObserver = {
5640      *   sum: 0,
5641      *   next(value) {
5642      *     console.log('Adding: ' + value);
5643      *     this.sum = this.sum + value;
5644      *   },
5645      *   error() { // We actually could just remote this method,
5646      *   },        // since we do not really care about errors right now.
5647      *   complete() {
5648      *     console.log('Sum equals: ' + this.sum);
5649      *   }
5650      * };
5651      *
5652      * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5653      * .subscribe(sumObserver);
5654      *
5655      * // Logs:
5656      * // "Adding: 1"
5657      * // "Adding: 2"
5658      * // "Adding: 3"
5659      * // "Sum equals: 6"
5660      *
5661      *
5662      * @example <caption>Subscribe with functions</caption>
5663      * let sum = 0;
5664      *
5665      * Rx.Observable.of(1, 2, 3)
5666      * .subscribe(
5667      *   function(value) {
5668      *     console.log('Adding: ' + value);
5669      *     sum = sum + value;
5670      *   },
5671      *   undefined,
5672      *   function() {
5673      *     console.log('Sum equals: ' + sum);
5674      *   }
5675      * );
5676      *
5677      * // Logs:
5678      * // "Adding: 1"
5679      * // "Adding: 2"
5680      * // "Adding: 3"
5681      * // "Sum equals: 6"
5682      *
5683      *
5684      * @example <caption>Cancel a subscription</caption>
5685      * const subscription = Rx.Observable.interval(1000).subscribe(
5686      *   num => console.log(num),
5687      *   undefined,
5688      *   () => console.log('completed!') // Will not be called, even
5689      * );                                // when cancelling subscription
5690      *
5691      *
5692      * setTimeout(() => {
5693      *   subscription.unsubscribe();
5694      *   console.log('unsubscribed!');
5695      * }, 2500);
5696      *
5697      * // Logs:
5698      * // 0 after 1s
5699      * // 1 after 2s
5700      * // "unsubscribed!" after 2,5s
5701      *
5702      *
5703      * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5704      *  or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5705      *  Observable.
5706      * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5707      *  the error will be thrown as unhandled.
5708      * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5709      * @return {ISubscription} a subscription reference to the registered handlers
5710      * @method subscribe
5711      */
5712     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5713         var operator = this.operator;
5714         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5715         if (operator) {
5716             operator.call(sink, this.source);
5717         }
5718         else {
5719             sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5720         }
5721         if (sink.syncErrorThrowable) {
5722             sink.syncErrorThrowable = false;
5723             if (sink.syncErrorThrown) {
5724                 throw sink.syncErrorValue;
5725             }
5726         }
5727         return sink;
5728     };
5729     Observable.prototype._trySubscribe = function (sink) {
5730         try {
5731             return this._subscribe(sink);
5732         }
5733         catch (err) {
5734             sink.syncErrorThrown = true;
5735             sink.syncErrorValue = err;
5736             sink.error(err);
5737         }
5738     };
5739     /**
5740      * @method forEach
5741      * @param {Function} next a handler for each value emitted by the observable
5742      * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5743      * @return {Promise} a promise that either resolves on observable completion or
5744      *  rejects with the handled error
5745      */
5746     Observable.prototype.forEach = function (next, PromiseCtor) {
5747         var _this = this;
5748         if (!PromiseCtor) {
5749             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5750                 PromiseCtor = root_1.root.Rx.config.Promise;
5751             }
5752             else if (root_1.root.Promise) {
5753                 PromiseCtor = root_1.root.Promise;
5754             }
5755         }
5756         if (!PromiseCtor) {
5757             throw new Error('no Promise impl found');
5758         }
5759         return new PromiseCtor(function (resolve, reject) {
5760             // Must be declared in a separate statement to avoid a RefernceError when
5761             // accessing subscription below in the closure due to Temporal Dead Zone.
5762             var subscription;
5763             subscription = _this.subscribe(function (value) {
5764                 if (subscription) {
5765                     // if there is a subscription, then we can surmise
5766                     // the next handling is asynchronous. Any errors thrown
5767                     // need to be rejected explicitly and unsubscribe must be
5768                     // called manually
5769                     try {
5770                         next(value);
5771                     }
5772                     catch (err) {
5773                         reject(err);
5774                         subscription.unsubscribe();
5775                     }
5776                 }
5777                 else {
5778                     // if there is NO subscription, then we're getting a nexted
5779                     // value synchronously during subscription. We can just call it.
5780                     // If it errors, Observable's `subscribe` will ensure the
5781                     // unsubscription logic is called, then synchronously rethrow the error.
5782                     // After that, Promise will trap the error and send it
5783                     // down the rejection path.
5784                     next(value);
5785                 }
5786             }, reject, resolve);
5787         });
5788     };
5789     Observable.prototype._subscribe = function (subscriber) {
5790         return this.source.subscribe(subscriber);
5791     };
5792     /**
5793      * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5794      * @method Symbol.observable
5795      * @return {Observable} this instance of the observable
5796      */
5797     Observable.prototype[observable_1.observable] = function () {
5798         return this;
5799     };
5800     // HACK: Since TypeScript inherits static properties too, we have to
5801     // fight against TypeScript here so Subject can have a different static create signature
5802     /**
5803      * Creates a new cold Observable by calling the Observable constructor
5804      * @static true
5805      * @owner Observable
5806      * @method create
5807      * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5808      * @return {Observable} a new cold observable
5809      */
5810     Observable.create = function (subscribe) {
5811         return new Observable(subscribe);
5812     };
5813     return Observable;
5814 }());
5815 exports.Observable = Observable;
5816
5817 },{"./symbol/observable":159,"./util/root":176,"./util/toSubscriber":178}],30:[function(require,module,exports){
5818 "use strict";
5819 exports.empty = {
5820     closed: true,
5821     next: function (value) { },
5822     error: function (err) { throw err; },
5823     complete: function () { }
5824 };
5825
5826 },{}],31:[function(require,module,exports){
5827 "use strict";
5828 var __extends = (this && this.__extends) || function (d, b) {
5829     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5830     function __() { this.constructor = d; }
5831     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5832 };
5833 var Subscriber_1 = require('./Subscriber');
5834 /**
5835  * We need this JSDoc comment for affecting ESDoc.
5836  * @ignore
5837  * @extends {Ignored}
5838  */
5839 var OuterSubscriber = (function (_super) {
5840     __extends(OuterSubscriber, _super);
5841     function OuterSubscriber() {
5842         _super.apply(this, arguments);
5843     }
5844     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5845         this.destination.next(innerValue);
5846     };
5847     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5848         this.destination.error(error);
5849     };
5850     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5851         this.destination.complete();
5852     };
5853     return OuterSubscriber;
5854 }(Subscriber_1.Subscriber));
5855 exports.OuterSubscriber = OuterSubscriber;
5856
5857 },{"./Subscriber":36}],32:[function(require,module,exports){
5858 "use strict";
5859 var __extends = (this && this.__extends) || function (d, b) {
5860     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5861     function __() { this.constructor = d; }
5862     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5863 };
5864 var Subject_1 = require('./Subject');
5865 var queue_1 = require('./scheduler/queue');
5866 var Subscription_1 = require('./Subscription');
5867 var observeOn_1 = require('./operator/observeOn');
5868 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5869 var SubjectSubscription_1 = require('./SubjectSubscription');
5870 /**
5871  * @class ReplaySubject<T>
5872  */
5873 var ReplaySubject = (function (_super) {
5874     __extends(ReplaySubject, _super);
5875     function ReplaySubject(bufferSize, windowTime, scheduler) {
5876         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5877         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5878         _super.call(this);
5879         this.scheduler = scheduler;
5880         this._events = [];
5881         this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5882         this._windowTime = windowTime < 1 ? 1 : windowTime;
5883     }
5884     ReplaySubject.prototype.next = function (value) {
5885         var now = this._getNow();
5886         this._events.push(new ReplayEvent(now, value));
5887         this._trimBufferThenGetEvents();
5888         _super.prototype.next.call(this, value);
5889     };
5890     ReplaySubject.prototype._subscribe = function (subscriber) {
5891         var _events = this._trimBufferThenGetEvents();
5892         var scheduler = this.scheduler;
5893         var subscription;
5894         if (this.closed) {
5895             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5896         }
5897         else if (this.hasError) {
5898             subscription = Subscription_1.Subscription.EMPTY;
5899         }
5900         else if (this.isStopped) {
5901             subscription = Subscription_1.Subscription.EMPTY;
5902         }
5903         else {
5904             this.observers.push(subscriber);
5905             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5906         }
5907         if (scheduler) {
5908             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5909         }
5910         var len = _events.length;
5911         for (var i = 0; i < len && !subscriber.closed; i++) {
5912             subscriber.next(_events[i].value);
5913         }
5914         if (this.hasError) {
5915             subscriber.error(this.thrownError);
5916         }
5917         else if (this.isStopped) {
5918             subscriber.complete();
5919         }
5920         return subscription;
5921     };
5922     ReplaySubject.prototype._getNow = function () {
5923         return (this.scheduler || queue_1.queue).now();
5924     };
5925     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5926         var now = this._getNow();
5927         var _bufferSize = this._bufferSize;
5928         var _windowTime = this._windowTime;
5929         var _events = this._events;
5930         var eventsCount = _events.length;
5931         var spliceCount = 0;
5932         // Trim events that fall out of the time window.
5933         // Start at the front of the list. Break early once
5934         // we encounter an event that falls within the window.
5935         while (spliceCount < eventsCount) {
5936             if ((now - _events[spliceCount].time) < _windowTime) {
5937                 break;
5938             }
5939             spliceCount++;
5940         }
5941         if (eventsCount > _bufferSize) {
5942             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5943         }
5944         if (spliceCount > 0) {
5945             _events.splice(0, spliceCount);
5946         }
5947         return _events;
5948     };
5949     return ReplaySubject;
5950 }(Subject_1.Subject));
5951 exports.ReplaySubject = ReplaySubject;
5952 var ReplayEvent = (function () {
5953     function ReplayEvent(time, value) {
5954         this.time = time;
5955         this.value = value;
5956     }
5957     return ReplayEvent;
5958 }());
5959
5960 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operator/observeOn":131,"./scheduler/queue":157,"./util/ObjectUnsubscribedError":164}],33:[function(require,module,exports){
5961 "use strict";
5962 /**
5963  * An execution context and a data structure to order tasks and schedule their
5964  * execution. Provides a notion of (potentially virtual) time, through the
5965  * `now()` getter method.
5966  *
5967  * Each unit of work in a Scheduler is called an {@link Action}.
5968  *
5969  * ```ts
5970  * class Scheduler {
5971  *   now(): number;
5972  *   schedule(work, delay?, state?): Subscription;
5973  * }
5974  * ```
5975  *
5976  * @class Scheduler
5977  */
5978 var Scheduler = (function () {
5979     function Scheduler(SchedulerAction, now) {
5980         if (now === void 0) { now = Scheduler.now; }
5981         this.SchedulerAction = SchedulerAction;
5982         this.now = now;
5983     }
5984     /**
5985      * Schedules a function, `work`, for execution. May happen at some point in
5986      * the future, according to the `delay` parameter, if specified. May be passed
5987      * some context object, `state`, which will be passed to the `work` function.
5988      *
5989      * The given arguments will be processed an stored as an Action object in a
5990      * queue of actions.
5991      *
5992      * @param {function(state: ?T): ?Subscription} work A function representing a
5993      * task, or some unit of work to be executed by the Scheduler.
5994      * @param {number} [delay] Time to wait before executing the work, where the
5995      * time unit is implicit and defined by the Scheduler itself.
5996      * @param {T} [state] Some contextual data that the `work` function uses when
5997      * called by the Scheduler.
5998      * @return {Subscription} A subscription in order to be able to unsubscribe
5999      * the scheduled work.
6000      */
6001     Scheduler.prototype.schedule = function (work, delay, state) {
6002         if (delay === void 0) { delay = 0; }
6003         return new this.SchedulerAction(this, work).schedule(state, delay);
6004     };
6005     Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6006     return Scheduler;
6007 }());
6008 exports.Scheduler = Scheduler;
6009
6010 },{}],34:[function(require,module,exports){
6011 "use strict";
6012 var __extends = (this && this.__extends) || function (d, b) {
6013     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6014     function __() { this.constructor = d; }
6015     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6016 };
6017 var Observable_1 = require('./Observable');
6018 var Subscriber_1 = require('./Subscriber');
6019 var Subscription_1 = require('./Subscription');
6020 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6021 var SubjectSubscription_1 = require('./SubjectSubscription');
6022 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6023 /**
6024  * @class SubjectSubscriber<T>
6025  */
6026 var SubjectSubscriber = (function (_super) {
6027     __extends(SubjectSubscriber, _super);
6028     function SubjectSubscriber(destination) {
6029         _super.call(this, destination);
6030         this.destination = destination;
6031     }
6032     return SubjectSubscriber;
6033 }(Subscriber_1.Subscriber));
6034 exports.SubjectSubscriber = SubjectSubscriber;
6035 /**
6036  * @class Subject<T>
6037  */
6038 var Subject = (function (_super) {
6039     __extends(Subject, _super);
6040     function Subject() {
6041         _super.call(this);
6042         this.observers = [];
6043         this.closed = false;
6044         this.isStopped = false;
6045         this.hasError = false;
6046         this.thrownError = null;
6047     }
6048     Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6049         return new SubjectSubscriber(this);
6050     };
6051     Subject.prototype.lift = function (operator) {
6052         var subject = new AnonymousSubject(this, this);
6053         subject.operator = operator;
6054         return subject;
6055     };
6056     Subject.prototype.next = function (value) {
6057         if (this.closed) {
6058             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6059         }
6060         if (!this.isStopped) {
6061             var observers = this.observers;
6062             var len = observers.length;
6063             var copy = observers.slice();
6064             for (var i = 0; i < len; i++) {
6065                 copy[i].next(value);
6066             }
6067         }
6068     };
6069     Subject.prototype.error = function (err) {
6070         if (this.closed) {
6071             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6072         }
6073         this.hasError = true;
6074         this.thrownError = err;
6075         this.isStopped = true;
6076         var observers = this.observers;
6077         var len = observers.length;
6078         var copy = observers.slice();
6079         for (var i = 0; i < len; i++) {
6080             copy[i].error(err);
6081         }
6082         this.observers.length = 0;
6083     };
6084     Subject.prototype.complete = function () {
6085         if (this.closed) {
6086             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6087         }
6088         this.isStopped = true;
6089         var observers = this.observers;
6090         var len = observers.length;
6091         var copy = observers.slice();
6092         for (var i = 0; i < len; i++) {
6093             copy[i].complete();
6094         }
6095         this.observers.length = 0;
6096     };
6097     Subject.prototype.unsubscribe = function () {
6098         this.isStopped = true;
6099         this.closed = true;
6100         this.observers = null;
6101     };
6102     Subject.prototype._trySubscribe = function (subscriber) {
6103         if (this.closed) {
6104             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6105         }
6106         else {
6107             return _super.prototype._trySubscribe.call(this, subscriber);
6108         }
6109     };
6110     Subject.prototype._subscribe = function (subscriber) {
6111         if (this.closed) {
6112             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6113         }
6114         else if (this.hasError) {
6115             subscriber.error(this.thrownError);
6116             return Subscription_1.Subscription.EMPTY;
6117         }
6118         else if (this.isStopped) {
6119             subscriber.complete();
6120             return Subscription_1.Subscription.EMPTY;
6121         }
6122         else {
6123             this.observers.push(subscriber);
6124             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6125         }
6126     };
6127     Subject.prototype.asObservable = function () {
6128         var observable = new Observable_1.Observable();
6129         observable.source = this;
6130         return observable;
6131     };
6132     Subject.create = function (destination, source) {
6133         return new AnonymousSubject(destination, source);
6134     };
6135     return Subject;
6136 }(Observable_1.Observable));
6137 exports.Subject = Subject;
6138 /**
6139  * @class AnonymousSubject<T>
6140  */
6141 var AnonymousSubject = (function (_super) {
6142     __extends(AnonymousSubject, _super);
6143     function AnonymousSubject(destination, source) {
6144         _super.call(this);
6145         this.destination = destination;
6146         this.source = source;
6147     }
6148     AnonymousSubject.prototype.next = function (value) {
6149         var destination = this.destination;
6150         if (destination && destination.next) {
6151             destination.next(value);
6152         }
6153     };
6154     AnonymousSubject.prototype.error = function (err) {
6155         var destination = this.destination;
6156         if (destination && destination.error) {
6157             this.destination.error(err);
6158         }
6159     };
6160     AnonymousSubject.prototype.complete = function () {
6161         var destination = this.destination;
6162         if (destination && destination.complete) {
6163             this.destination.complete();
6164         }
6165     };
6166     AnonymousSubject.prototype._subscribe = function (subscriber) {
6167         var source = this.source;
6168         if (source) {
6169             return this.source.subscribe(subscriber);
6170         }
6171         else {
6172             return Subscription_1.Subscription.EMPTY;
6173         }
6174     };
6175     return AnonymousSubject;
6176 }(Subject));
6177 exports.AnonymousSubject = AnonymousSubject;
6178
6179 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":160,"./util/ObjectUnsubscribedError":164}],35:[function(require,module,exports){
6180 "use strict";
6181 var __extends = (this && this.__extends) || function (d, b) {
6182     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6183     function __() { this.constructor = d; }
6184     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6185 };
6186 var Subscription_1 = require('./Subscription');
6187 /**
6188  * We need this JSDoc comment for affecting ESDoc.
6189  * @ignore
6190  * @extends {Ignored}
6191  */
6192 var SubjectSubscription = (function (_super) {
6193     __extends(SubjectSubscription, _super);
6194     function SubjectSubscription(subject, subscriber) {
6195         _super.call(this);
6196         this.subject = subject;
6197         this.subscriber = subscriber;
6198         this.closed = false;
6199     }
6200     SubjectSubscription.prototype.unsubscribe = function () {
6201         if (this.closed) {
6202             return;
6203         }
6204         this.closed = true;
6205         var subject = this.subject;
6206         var observers = subject.observers;
6207         this.subject = null;
6208         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6209             return;
6210         }
6211         var subscriberIndex = observers.indexOf(this.subscriber);
6212         if (subscriberIndex !== -1) {
6213             observers.splice(subscriberIndex, 1);
6214         }
6215     };
6216     return SubjectSubscription;
6217 }(Subscription_1.Subscription));
6218 exports.SubjectSubscription = SubjectSubscription;
6219
6220 },{"./Subscription":37}],36:[function(require,module,exports){
6221 "use strict";
6222 var __extends = (this && this.__extends) || function (d, b) {
6223     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6224     function __() { this.constructor = d; }
6225     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6226 };
6227 var isFunction_1 = require('./util/isFunction');
6228 var Subscription_1 = require('./Subscription');
6229 var Observer_1 = require('./Observer');
6230 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6231 /**
6232  * Implements the {@link Observer} interface and extends the
6233  * {@link Subscription} class. While the {@link Observer} is the public API for
6234  * consuming the values of an {@link Observable}, all Observers get converted to
6235  * a Subscriber, in order to provide Subscription-like capabilities such as
6236  * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6237  * implementing operators, but it is rarely used as a public API.
6238  *
6239  * @class Subscriber<T>
6240  */
6241 var Subscriber = (function (_super) {
6242     __extends(Subscriber, _super);
6243     /**
6244      * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6245      * defined Observer or a `next` callback function.
6246      * @param {function(e: ?any): void} [error] The `error` callback of an
6247      * Observer.
6248      * @param {function(): void} [complete] The `complete` callback of an
6249      * Observer.
6250      */
6251     function Subscriber(destinationOrNext, error, complete) {
6252         _super.call(this);
6253         this.syncErrorValue = null;
6254         this.syncErrorThrown = false;
6255         this.syncErrorThrowable = false;
6256         this.isStopped = false;
6257         switch (arguments.length) {
6258             case 0:
6259                 this.destination = Observer_1.empty;
6260                 break;
6261             case 1:
6262                 if (!destinationOrNext) {
6263                     this.destination = Observer_1.empty;
6264                     break;
6265                 }
6266                 if (typeof destinationOrNext === 'object') {
6267                     if (destinationOrNext instanceof Subscriber) {
6268                         this.destination = destinationOrNext;
6269                         this.destination.add(this);
6270                     }
6271                     else {
6272                         this.syncErrorThrowable = true;
6273                         this.destination = new SafeSubscriber(this, destinationOrNext);
6274                     }
6275                     break;
6276                 }
6277             default:
6278                 this.syncErrorThrowable = true;
6279                 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6280                 break;
6281         }
6282     }
6283     Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6284     /**
6285      * A static factory for a Subscriber, given a (potentially partial) definition
6286      * of an Observer.
6287      * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6288      * @param {function(e: ?any): void} [error] The `error` callback of an
6289      * Observer.
6290      * @param {function(): void} [complete] The `complete` callback of an
6291      * Observer.
6292      * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6293      * Observer represented by the given arguments.
6294      */
6295     Subscriber.create = function (next, error, complete) {
6296         var subscriber = new Subscriber(next, error, complete);
6297         subscriber.syncErrorThrowable = false;
6298         return subscriber;
6299     };
6300     /**
6301      * The {@link Observer} callback to receive notifications of type `next` from
6302      * the Observable, with a value. The Observable may call this method 0 or more
6303      * times.
6304      * @param {T} [value] The `next` value.
6305      * @return {void}
6306      */
6307     Subscriber.prototype.next = function (value) {
6308         if (!this.isStopped) {
6309             this._next(value);
6310         }
6311     };
6312     /**
6313      * The {@link Observer} callback to receive notifications of type `error` from
6314      * the Observable, with an attached {@link Error}. Notifies the Observer that
6315      * the Observable has experienced an error condition.
6316      * @param {any} [err] The `error` exception.
6317      * @return {void}
6318      */
6319     Subscriber.prototype.error = function (err) {
6320         if (!this.isStopped) {
6321             this.isStopped = true;
6322             this._error(err);
6323         }
6324     };
6325     /**
6326      * The {@link Observer} callback to receive a valueless notification of type
6327      * `complete` from the Observable. Notifies the Observer that the Observable
6328      * has finished sending push-based notifications.
6329      * @return {void}
6330      */
6331     Subscriber.prototype.complete = function () {
6332         if (!this.isStopped) {
6333             this.isStopped = true;
6334             this._complete();
6335         }
6336     };
6337     Subscriber.prototype.unsubscribe = function () {
6338         if (this.closed) {
6339             return;
6340         }
6341         this.isStopped = true;
6342         _super.prototype.unsubscribe.call(this);
6343     };
6344     Subscriber.prototype._next = function (value) {
6345         this.destination.next(value);
6346     };
6347     Subscriber.prototype._error = function (err) {
6348         this.destination.error(err);
6349         this.unsubscribe();
6350     };
6351     Subscriber.prototype._complete = function () {
6352         this.destination.complete();
6353         this.unsubscribe();
6354     };
6355     Subscriber.prototype._unsubscribeAndRecycle = function () {
6356         var _a = this, _parent = _a._parent, _parents = _a._parents;
6357         this._parent = null;
6358         this._parents = null;
6359         this.unsubscribe();
6360         this.closed = false;
6361         this.isStopped = false;
6362         this._parent = _parent;
6363         this._parents = _parents;
6364         return this;
6365     };
6366     return Subscriber;
6367 }(Subscription_1.Subscription));
6368 exports.Subscriber = Subscriber;
6369 /**
6370  * We need this JSDoc comment for affecting ESDoc.
6371  * @ignore
6372  * @extends {Ignored}
6373  */
6374 var SafeSubscriber = (function (_super) {
6375     __extends(SafeSubscriber, _super);
6376     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6377         _super.call(this);
6378         this._parentSubscriber = _parentSubscriber;
6379         var next;
6380         var context = this;
6381         if (isFunction_1.isFunction(observerOrNext)) {
6382             next = observerOrNext;
6383         }
6384         else if (observerOrNext) {
6385             next = observerOrNext.next;
6386             error = observerOrNext.error;
6387             complete = observerOrNext.complete;
6388             if (observerOrNext !== Observer_1.empty) {
6389                 context = Object.create(observerOrNext);
6390                 if (isFunction_1.isFunction(context.unsubscribe)) {
6391                     this.add(context.unsubscribe.bind(context));
6392                 }
6393                 context.unsubscribe = this.unsubscribe.bind(this);
6394             }
6395         }
6396         this._context = context;
6397         this._next = next;
6398         this._error = error;
6399         this._complete = complete;
6400     }
6401     SafeSubscriber.prototype.next = function (value) {
6402         if (!this.isStopped && this._next) {
6403             var _parentSubscriber = this._parentSubscriber;
6404             if (!_parentSubscriber.syncErrorThrowable) {
6405                 this.__tryOrUnsub(this._next, value);
6406             }
6407             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6408                 this.unsubscribe();
6409             }
6410         }
6411     };
6412     SafeSubscriber.prototype.error = function (err) {
6413         if (!this.isStopped) {
6414             var _parentSubscriber = this._parentSubscriber;
6415             if (this._error) {
6416                 if (!_parentSubscriber.syncErrorThrowable) {
6417                     this.__tryOrUnsub(this._error, err);
6418                     this.unsubscribe();
6419                 }
6420                 else {
6421                     this.__tryOrSetError(_parentSubscriber, this._error, err);
6422                     this.unsubscribe();
6423                 }
6424             }
6425             else if (!_parentSubscriber.syncErrorThrowable) {
6426                 this.unsubscribe();
6427                 throw err;
6428             }
6429             else {
6430                 _parentSubscriber.syncErrorValue = err;
6431                 _parentSubscriber.syncErrorThrown = true;
6432                 this.unsubscribe();
6433             }
6434         }
6435     };
6436     SafeSubscriber.prototype.complete = function () {
6437         var _this = this;
6438         if (!this.isStopped) {
6439             var _parentSubscriber = this._parentSubscriber;
6440             if (this._complete) {
6441                 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6442                 if (!_parentSubscriber.syncErrorThrowable) {
6443                     this.__tryOrUnsub(wrappedComplete);
6444                     this.unsubscribe();
6445                 }
6446                 else {
6447                     this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6448                     this.unsubscribe();
6449                 }
6450             }
6451             else {
6452                 this.unsubscribe();
6453             }
6454         }
6455     };
6456     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6457         try {
6458             fn.call(this._context, value);
6459         }
6460         catch (err) {
6461             this.unsubscribe();
6462             throw err;
6463         }
6464     };
6465     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6466         try {
6467             fn.call(this._context, value);
6468         }
6469         catch (err) {
6470             parent.syncErrorValue = err;
6471             parent.syncErrorThrown = true;
6472             return true;
6473         }
6474         return false;
6475     };
6476     SafeSubscriber.prototype._unsubscribe = function () {
6477         var _parentSubscriber = this._parentSubscriber;
6478         this._context = null;
6479         this._parentSubscriber = null;
6480         _parentSubscriber.unsubscribe();
6481     };
6482     return SafeSubscriber;
6483 }(Subscriber));
6484
6485 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":160,"./util/isFunction":171}],37:[function(require,module,exports){
6486 "use strict";
6487 var isArray_1 = require('./util/isArray');
6488 var isObject_1 = require('./util/isObject');
6489 var isFunction_1 = require('./util/isFunction');
6490 var tryCatch_1 = require('./util/tryCatch');
6491 var errorObject_1 = require('./util/errorObject');
6492 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6493 /**
6494  * Represents a disposable resource, such as the execution of an Observable. A
6495  * Subscription has one important method, `unsubscribe`, that takes no argument
6496  * and just disposes the resource held by the subscription.
6497  *
6498  * Additionally, subscriptions may be grouped together through the `add()`
6499  * method, which will attach a child Subscription to the current Subscription.
6500  * When a Subscription is unsubscribed, all its children (and its grandchildren)
6501  * will be unsubscribed as well.
6502  *
6503  * @class Subscription
6504  */
6505 var Subscription = (function () {
6506     /**
6507      * @param {function(): void} [unsubscribe] A function describing how to
6508      * perform the disposal of resources when the `unsubscribe` method is called.
6509      */
6510     function Subscription(unsubscribe) {
6511         /**
6512          * A flag to indicate whether this Subscription has already been unsubscribed.
6513          * @type {boolean}
6514          */
6515         this.closed = false;
6516         this._parent = null;
6517         this._parents = null;
6518         this._subscriptions = null;
6519         if (unsubscribe) {
6520             this._unsubscribe = unsubscribe;
6521         }
6522     }
6523     /**
6524      * Disposes the resources held by the subscription. May, for instance, cancel
6525      * an ongoing Observable execution or cancel any other type of work that
6526      * started when the Subscription was created.
6527      * @return {void}
6528      */
6529     Subscription.prototype.unsubscribe = function () {
6530         var hasErrors = false;
6531         var errors;
6532         if (this.closed) {
6533             return;
6534         }
6535         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6536         this.closed = true;
6537         this._parent = null;
6538         this._parents = null;
6539         // null out _subscriptions first so any child subscriptions that attempt
6540         // to remove themselves from this subscription will noop
6541         this._subscriptions = null;
6542         var index = -1;
6543         var len = _parents ? _parents.length : 0;
6544         // if this._parent is null, then so is this._parents, and we
6545         // don't have to remove ourselves from any parent subscriptions.
6546         while (_parent) {
6547             _parent.remove(this);
6548             // if this._parents is null or index >= len,
6549             // then _parent is set to null, and the loop exits
6550             _parent = ++index < len && _parents[index] || null;
6551         }
6552         if (isFunction_1.isFunction(_unsubscribe)) {
6553             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6554             if (trial === errorObject_1.errorObject) {
6555                 hasErrors = true;
6556                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6557                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6558             }
6559         }
6560         if (isArray_1.isArray(_subscriptions)) {
6561             index = -1;
6562             len = _subscriptions.length;
6563             while (++index < len) {
6564                 var sub = _subscriptions[index];
6565                 if (isObject_1.isObject(sub)) {
6566                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6567                     if (trial === errorObject_1.errorObject) {
6568                         hasErrors = true;
6569                         errors = errors || [];
6570                         var err = errorObject_1.errorObject.e;
6571                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6572                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6573                         }
6574                         else {
6575                             errors.push(err);
6576                         }
6577                     }
6578                 }
6579             }
6580         }
6581         if (hasErrors) {
6582             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6583         }
6584     };
6585     /**
6586      * Adds a tear down to be called during the unsubscribe() of this
6587      * Subscription.
6588      *
6589      * If the tear down being added is a subscription that is already
6590      * unsubscribed, is the same reference `add` is being called on, or is
6591      * `Subscription.EMPTY`, it will not be added.
6592      *
6593      * If this subscription is already in an `closed` state, the passed
6594      * tear down logic will be executed immediately.
6595      *
6596      * @param {TeardownLogic} teardown The additional logic to execute on
6597      * teardown.
6598      * @return {Subscription} Returns the Subscription used or created to be
6599      * added to the inner subscriptions list. This Subscription can be used with
6600      * `remove()` to remove the passed teardown logic from the inner subscriptions
6601      * list.
6602      */
6603     Subscription.prototype.add = function (teardown) {
6604         if (!teardown || (teardown === Subscription.EMPTY)) {
6605             return Subscription.EMPTY;
6606         }
6607         if (teardown === this) {
6608             return this;
6609         }
6610         var subscription = teardown;
6611         switch (typeof teardown) {
6612             case 'function':
6613                 subscription = new Subscription(teardown);
6614             case 'object':
6615                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6616                     return subscription;
6617                 }
6618                 else if (this.closed) {
6619                     subscription.unsubscribe();
6620                     return subscription;
6621                 }
6622                 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6623                     var tmp = subscription;
6624                     subscription = new Subscription();
6625                     subscription._subscriptions = [tmp];
6626                 }
6627                 break;
6628             default:
6629                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6630         }
6631         var subscriptions = this._subscriptions || (this._subscriptions = []);
6632         subscriptions.push(subscription);
6633         subscription._addParent(this);
6634         return subscription;
6635     };
6636     /**
6637      * Removes a Subscription from the internal list of subscriptions that will
6638      * unsubscribe during the unsubscribe process of this Subscription.
6639      * @param {Subscription} subscription The subscription to remove.
6640      * @return {void}
6641      */
6642     Subscription.prototype.remove = function (subscription) {
6643         var subscriptions = this._subscriptions;
6644         if (subscriptions) {
6645             var subscriptionIndex = subscriptions.indexOf(subscription);
6646             if (subscriptionIndex !== -1) {
6647                 subscriptions.splice(subscriptionIndex, 1);
6648             }
6649         }
6650     };
6651     Subscription.prototype._addParent = function (parent) {
6652         var _a = this, _parent = _a._parent, _parents = _a._parents;
6653         if (!_parent || _parent === parent) {
6654             // If we don't have a parent, or the new parent is the same as the
6655             // current parent, then set this._parent to the new parent.
6656             this._parent = parent;
6657         }
6658         else if (!_parents) {
6659             // If there's already one parent, but not multiple, allocate an Array to
6660             // store the rest of the parent Subscriptions.
6661             this._parents = [parent];
6662         }
6663         else if (_parents.indexOf(parent) === -1) {
6664             // Only add the new parent to the _parents list if it's not already there.
6665             _parents.push(parent);
6666         }
6667     };
6668     Subscription.EMPTY = (function (empty) {
6669         empty.closed = true;
6670         return empty;
6671     }(new Subscription()));
6672     return Subscription;
6673 }());
6674 exports.Subscription = Subscription;
6675 function flattenUnsubscriptionErrors(errors) {
6676     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6677 }
6678
6679 },{"./util/UnsubscriptionError":166,"./util/errorObject":167,"./util/isArray":168,"./util/isFunction":171,"./util/isObject":173,"./util/tryCatch":179}],38:[function(require,module,exports){
6680 "use strict";
6681 var Observable_1 = require('../../Observable');
6682 var combineLatest_1 = require('../../observable/combineLatest');
6683 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6684
6685 },{"../../Observable":29,"../../observable/combineLatest":99}],39:[function(require,module,exports){
6686 "use strict";
6687 var Observable_1 = require('../../Observable');
6688 var defer_1 = require('../../observable/defer');
6689 Observable_1.Observable.defer = defer_1.defer;
6690
6691 },{"../../Observable":29,"../../observable/defer":100}],40:[function(require,module,exports){
6692 "use strict";
6693 var Observable_1 = require('../../Observable');
6694 var empty_1 = require('../../observable/empty');
6695 Observable_1.Observable.empty = empty_1.empty;
6696
6697 },{"../../Observable":29,"../../observable/empty":101}],41:[function(require,module,exports){
6698 "use strict";
6699 var Observable_1 = require('../../Observable');
6700 var from_1 = require('../../observable/from');
6701 Observable_1.Observable.from = from_1.from;
6702
6703 },{"../../Observable":29,"../../observable/from":102}],42:[function(require,module,exports){
6704 "use strict";
6705 var Observable_1 = require('../../Observable');
6706 var fromEvent_1 = require('../../observable/fromEvent');
6707 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6708
6709 },{"../../Observable":29,"../../observable/fromEvent":103}],43:[function(require,module,exports){
6710 "use strict";
6711 var Observable_1 = require('../../Observable');
6712 var fromPromise_1 = require('../../observable/fromPromise');
6713 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6714
6715 },{"../../Observable":29,"../../observable/fromPromise":104}],44:[function(require,module,exports){
6716 "use strict";
6717 var Observable_1 = require('../../Observable');
6718 var merge_1 = require('../../observable/merge');
6719 Observable_1.Observable.merge = merge_1.merge;
6720
6721 },{"../../Observable":29,"../../observable/merge":105}],45:[function(require,module,exports){
6722 "use strict";
6723 var Observable_1 = require('../../Observable');
6724 var of_1 = require('../../observable/of');
6725 Observable_1.Observable.of = of_1.of;
6726
6727 },{"../../Observable":29,"../../observable/of":106}],46:[function(require,module,exports){
6728 "use strict";
6729 var Observable_1 = require('../../Observable');
6730 var throw_1 = require('../../observable/throw');
6731 Observable_1.Observable.throw = throw_1._throw;
6732
6733 },{"../../Observable":29,"../../observable/throw":107}],47:[function(require,module,exports){
6734 "use strict";
6735 var Observable_1 = require('../../Observable');
6736 var timer_1 = require('../../observable/timer');
6737 Observable_1.Observable.timer = timer_1.timer;
6738
6739 },{"../../Observable":29,"../../observable/timer":108}],48:[function(require,module,exports){
6740 "use strict";
6741 var Observable_1 = require('../../Observable');
6742 var zip_1 = require('../../observable/zip');
6743 Observable_1.Observable.zip = zip_1.zip;
6744
6745 },{"../../Observable":29,"../../observable/zip":109}],49:[function(require,module,exports){
6746 "use strict";
6747 var Observable_1 = require('../../Observable');
6748 var buffer_1 = require('../../operator/buffer');
6749 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6750
6751 },{"../../Observable":29,"../../operator/buffer":110}],50:[function(require,module,exports){
6752 "use strict";
6753 var Observable_1 = require('../../Observable');
6754 var bufferCount_1 = require('../../operator/bufferCount');
6755 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6756
6757 },{"../../Observable":29,"../../operator/bufferCount":111}],51:[function(require,module,exports){
6758 "use strict";
6759 var Observable_1 = require('../../Observable');
6760 var bufferWhen_1 = require('../../operator/bufferWhen');
6761 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6762
6763 },{"../../Observable":29,"../../operator/bufferWhen":112}],52:[function(require,module,exports){
6764 "use strict";
6765 var Observable_1 = require('../../Observable');
6766 var catch_1 = require('../../operator/catch');
6767 Observable_1.Observable.prototype.catch = catch_1._catch;
6768 Observable_1.Observable.prototype._catch = catch_1._catch;
6769
6770 },{"../../Observable":29,"../../operator/catch":113}],53:[function(require,module,exports){
6771 "use strict";
6772 var Observable_1 = require('../../Observable');
6773 var combineLatest_1 = require('../../operator/combineLatest');
6774 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6775
6776 },{"../../Observable":29,"../../operator/combineLatest":114}],54:[function(require,module,exports){
6777 "use strict";
6778 var Observable_1 = require('../../Observable');
6779 var concat_1 = require('../../operator/concat');
6780 Observable_1.Observable.prototype.concat = concat_1.concat;
6781
6782 },{"../../Observable":29,"../../operator/concat":115}],55:[function(require,module,exports){
6783 "use strict";
6784 var Observable_1 = require('../../Observable');
6785 var debounceTime_1 = require('../../operator/debounceTime');
6786 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6787
6788 },{"../../Observable":29,"../../operator/debounceTime":116}],56:[function(require,module,exports){
6789 "use strict";
6790 var Observable_1 = require('../../Observable');
6791 var delay_1 = require('../../operator/delay');
6792 Observable_1.Observable.prototype.delay = delay_1.delay;
6793
6794 },{"../../Observable":29,"../../operator/delay":117}],57:[function(require,module,exports){
6795 "use strict";
6796 var Observable_1 = require('../../Observable');
6797 var distinct_1 = require('../../operator/distinct');
6798 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6799
6800 },{"../../Observable":29,"../../operator/distinct":118}],58:[function(require,module,exports){
6801 "use strict";
6802 var Observable_1 = require('../../Observable');
6803 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6804 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6805
6806 },{"../../Observable":29,"../../operator/distinctUntilChanged":119}],59:[function(require,module,exports){
6807 "use strict";
6808 var Observable_1 = require('../../Observable');
6809 var do_1 = require('../../operator/do');
6810 Observable_1.Observable.prototype.do = do_1._do;
6811 Observable_1.Observable.prototype._do = do_1._do;
6812
6813 },{"../../Observable":29,"../../operator/do":120}],60:[function(require,module,exports){
6814 "use strict";
6815 var Observable_1 = require('../../Observable');
6816 var expand_1 = require('../../operator/expand');
6817 Observable_1.Observable.prototype.expand = expand_1.expand;
6818
6819 },{"../../Observable":29,"../../operator/expand":121}],61:[function(require,module,exports){
6820 "use strict";
6821 var Observable_1 = require('../../Observable');
6822 var filter_1 = require('../../operator/filter');
6823 Observable_1.Observable.prototype.filter = filter_1.filter;
6824
6825 },{"../../Observable":29,"../../operator/filter":122}],62:[function(require,module,exports){
6826 "use strict";
6827 var Observable_1 = require('../../Observable');
6828 var finally_1 = require('../../operator/finally');
6829 Observable_1.Observable.prototype.finally = finally_1._finally;
6830 Observable_1.Observable.prototype._finally = finally_1._finally;
6831
6832 },{"../../Observable":29,"../../operator/finally":123}],63:[function(require,module,exports){
6833 "use strict";
6834 var Observable_1 = require('../../Observable');
6835 var first_1 = require('../../operator/first');
6836 Observable_1.Observable.prototype.first = first_1.first;
6837
6838 },{"../../Observable":29,"../../operator/first":124}],64:[function(require,module,exports){
6839 "use strict";
6840 var Observable_1 = require('../../Observable');
6841 var last_1 = require('../../operator/last');
6842 Observable_1.Observable.prototype.last = last_1.last;
6843
6844 },{"../../Observable":29,"../../operator/last":125}],65:[function(require,module,exports){
6845 "use strict";
6846 var Observable_1 = require('../../Observable');
6847 var map_1 = require('../../operator/map');
6848 Observable_1.Observable.prototype.map = map_1.map;
6849
6850 },{"../../Observable":29,"../../operator/map":126}],66:[function(require,module,exports){
6851 "use strict";
6852 var Observable_1 = require('../../Observable');
6853 var merge_1 = require('../../operator/merge');
6854 Observable_1.Observable.prototype.merge = merge_1.merge;
6855
6856 },{"../../Observable":29,"../../operator/merge":127}],67:[function(require,module,exports){
6857 "use strict";
6858 var Observable_1 = require('../../Observable');
6859 var mergeAll_1 = require('../../operator/mergeAll');
6860 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6861
6862 },{"../../Observable":29,"../../operator/mergeAll":128}],68:[function(require,module,exports){
6863 "use strict";
6864 var Observable_1 = require('../../Observable');
6865 var mergeMap_1 = require('../../operator/mergeMap');
6866 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6867 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6868
6869 },{"../../Observable":29,"../../operator/mergeMap":129}],69:[function(require,module,exports){
6870 "use strict";
6871 var Observable_1 = require('../../Observable');
6872 var pairwise_1 = require('../../operator/pairwise');
6873 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6874
6875 },{"../../Observable":29,"../../operator/pairwise":132}],70:[function(require,module,exports){
6876 "use strict";
6877 var Observable_1 = require('../../Observable');
6878 var pluck_1 = require('../../operator/pluck');
6879 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6880
6881 },{"../../Observable":29,"../../operator/pluck":133}],71:[function(require,module,exports){
6882 "use strict";
6883 var Observable_1 = require('../../Observable');
6884 var publish_1 = require('../../operator/publish');
6885 Observable_1.Observable.prototype.publish = publish_1.publish;
6886
6887 },{"../../Observable":29,"../../operator/publish":134}],72:[function(require,module,exports){
6888 "use strict";
6889 var Observable_1 = require('../../Observable');
6890 var publishReplay_1 = require('../../operator/publishReplay');
6891 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6892
6893 },{"../../Observable":29,"../../operator/publishReplay":135}],73:[function(require,module,exports){
6894 "use strict";
6895 var Observable_1 = require('../../Observable');
6896 var sample_1 = require('../../operator/sample');
6897 Observable_1.Observable.prototype.sample = sample_1.sample;
6898
6899 },{"../../Observable":29,"../../operator/sample":136}],74:[function(require,module,exports){
6900 "use strict";
6901 var Observable_1 = require('../../Observable');
6902 var scan_1 = require('../../operator/scan');
6903 Observable_1.Observable.prototype.scan = scan_1.scan;
6904
6905 },{"../../Observable":29,"../../operator/scan":137}],75:[function(require,module,exports){
6906 "use strict";
6907 var Observable_1 = require('../../Observable');
6908 var share_1 = require('../../operator/share');
6909 Observable_1.Observable.prototype.share = share_1.share;
6910
6911 },{"../../Observable":29,"../../operator/share":138}],76:[function(require,module,exports){
6912 "use strict";
6913 var Observable_1 = require('../../Observable');
6914 var skip_1 = require('../../operator/skip');
6915 Observable_1.Observable.prototype.skip = skip_1.skip;
6916
6917 },{"../../Observable":29,"../../operator/skip":139}],77:[function(require,module,exports){
6918 "use strict";
6919 var Observable_1 = require('../../Observable');
6920 var skipUntil_1 = require('../../operator/skipUntil');
6921 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6922
6923 },{"../../Observable":29,"../../operator/skipUntil":140}],78:[function(require,module,exports){
6924 "use strict";
6925 var Observable_1 = require('../../Observable');
6926 var skipWhile_1 = require('../../operator/skipWhile');
6927 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6928
6929 },{"../../Observable":29,"../../operator/skipWhile":141}],79:[function(require,module,exports){
6930 "use strict";
6931 var Observable_1 = require('../../Observable');
6932 var startWith_1 = require('../../operator/startWith');
6933 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6934
6935 },{"../../Observable":29,"../../operator/startWith":142}],80:[function(require,module,exports){
6936 "use strict";
6937 var Observable_1 = require('../../Observable');
6938 var switchMap_1 = require('../../operator/switchMap');
6939 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6940
6941 },{"../../Observable":29,"../../operator/switchMap":143}],81:[function(require,module,exports){
6942 "use strict";
6943 var Observable_1 = require('../../Observable');
6944 var take_1 = require('../../operator/take');
6945 Observable_1.Observable.prototype.take = take_1.take;
6946
6947 },{"../../Observable":29,"../../operator/take":144}],82:[function(require,module,exports){
6948 "use strict";
6949 var Observable_1 = require('../../Observable');
6950 var takeUntil_1 = require('../../operator/takeUntil');
6951 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6952
6953 },{"../../Observable":29,"../../operator/takeUntil":145}],83:[function(require,module,exports){
6954 "use strict";
6955 var Observable_1 = require('../../Observable');
6956 var takeWhile_1 = require('../../operator/takeWhile');
6957 Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile;
6958
6959 },{"../../Observable":29,"../../operator/takeWhile":146}],84:[function(require,module,exports){
6960 "use strict";
6961 var Observable_1 = require('../../Observable');
6962 var throttleTime_1 = require('../../operator/throttleTime');
6963 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6964
6965 },{"../../Observable":29,"../../operator/throttleTime":148}],85:[function(require,module,exports){
6966 "use strict";
6967 var Observable_1 = require('../../Observable');
6968 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6969 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6970
6971 },{"../../Observable":29,"../../operator/withLatestFrom":149}],86:[function(require,module,exports){
6972 "use strict";
6973 var Observable_1 = require('../../Observable');
6974 var zip_1 = require('../../operator/zip');
6975 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6976
6977 },{"../../Observable":29,"../../operator/zip":150}],87:[function(require,module,exports){
6978 "use strict";
6979 var __extends = (this && this.__extends) || function (d, b) {
6980     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6981     function __() { this.constructor = d; }
6982     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6983 };
6984 var Observable_1 = require('../Observable');
6985 var ScalarObservable_1 = require('./ScalarObservable');
6986 var EmptyObservable_1 = require('./EmptyObservable');
6987 /**
6988  * We need this JSDoc comment for affecting ESDoc.
6989  * @extends {Ignored}
6990  * @hide true
6991  */
6992 var ArrayLikeObservable = (function (_super) {
6993     __extends(ArrayLikeObservable, _super);
6994     function ArrayLikeObservable(arrayLike, scheduler) {
6995         _super.call(this);
6996         this.arrayLike = arrayLike;
6997         this.scheduler = scheduler;
6998         if (!scheduler && arrayLike.length === 1) {
6999             this._isScalar = true;
7000             this.value = arrayLike[0];
7001         }
7002     }
7003     ArrayLikeObservable.create = function (arrayLike, scheduler) {
7004         var length = arrayLike.length;
7005         if (length === 0) {
7006             return new EmptyObservable_1.EmptyObservable();
7007         }
7008         else if (length === 1) {
7009             return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7010         }
7011         else {
7012             return new ArrayLikeObservable(arrayLike, scheduler);
7013         }
7014     };
7015     ArrayLikeObservable.dispatch = function (state) {
7016         var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7017         if (subscriber.closed) {
7018             return;
7019         }
7020         if (index >= length) {
7021             subscriber.complete();
7022             return;
7023         }
7024         subscriber.next(arrayLike[index]);
7025         state.index = index + 1;
7026         this.schedule(state);
7027     };
7028     ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7029         var index = 0;
7030         var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7031         var length = arrayLike.length;
7032         if (scheduler) {
7033             return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7034                 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7035             });
7036         }
7037         else {
7038             for (var i = 0; i < length && !subscriber.closed; i++) {
7039                 subscriber.next(arrayLike[i]);
7040             }
7041             subscriber.complete();
7042         }
7043     };
7044     return ArrayLikeObservable;
7045 }(Observable_1.Observable));
7046 exports.ArrayLikeObservable = ArrayLikeObservable;
7047
7048 },{"../Observable":29,"./EmptyObservable":91,"./ScalarObservable":97}],88:[function(require,module,exports){
7049 "use strict";
7050 var __extends = (this && this.__extends) || function (d, b) {
7051     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7052     function __() { this.constructor = d; }
7053     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7054 };
7055 var Observable_1 = require('../Observable');
7056 var ScalarObservable_1 = require('./ScalarObservable');
7057 var EmptyObservable_1 = require('./EmptyObservable');
7058 var isScheduler_1 = require('../util/isScheduler');
7059 /**
7060  * We need this JSDoc comment for affecting ESDoc.
7061  * @extends {Ignored}
7062  * @hide true
7063  */
7064 var ArrayObservable = (function (_super) {
7065     __extends(ArrayObservable, _super);
7066     function ArrayObservable(array, scheduler) {
7067         _super.call(this);
7068         this.array = array;
7069         this.scheduler = scheduler;
7070         if (!scheduler && array.length === 1) {
7071             this._isScalar = true;
7072             this.value = array[0];
7073         }
7074     }
7075     ArrayObservable.create = function (array, scheduler) {
7076         return new ArrayObservable(array, scheduler);
7077     };
7078     /**
7079      * Creates an Observable that emits some values you specify as arguments,
7080      * immediately one after the other, and then emits a complete notification.
7081      *
7082      * <span class="informal">Emits the arguments you provide, then completes.
7083      * </span>
7084      *
7085      * <img src="./img/of.png" width="100%">
7086      *
7087      * This static operator is useful for creating a simple Observable that only
7088      * emits the arguments given, and the complete notification thereafter. It can
7089      * be used for composing with other Observables, such as with {@link concat}.
7090      * By default, it uses a `null` IScheduler, which means the `next`
7091      * notifications are sent synchronously, although with a different IScheduler
7092      * it is possible to determine when those notifications will be delivered.
7093      *
7094      * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7095      * var numbers = Rx.Observable.of(10, 20, 30);
7096      * var letters = Rx.Observable.of('a', 'b', 'c');
7097      * var interval = Rx.Observable.interval(1000);
7098      * var result = numbers.concat(letters).concat(interval);
7099      * result.subscribe(x => console.log(x));
7100      *
7101      * @see {@link create}
7102      * @see {@link empty}
7103      * @see {@link never}
7104      * @see {@link throw}
7105      *
7106      * @param {...T} values Arguments that represent `next` values to be emitted.
7107      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7108      * the emissions of the `next` notifications.
7109      * @return {Observable<T>} An Observable that emits each given input value.
7110      * @static true
7111      * @name of
7112      * @owner Observable
7113      */
7114     ArrayObservable.of = function () {
7115         var array = [];
7116         for (var _i = 0; _i < arguments.length; _i++) {
7117             array[_i - 0] = arguments[_i];
7118         }
7119         var scheduler = array[array.length - 1];
7120         if (isScheduler_1.isScheduler(scheduler)) {
7121             array.pop();
7122         }
7123         else {
7124             scheduler = null;
7125         }
7126         var len = array.length;
7127         if (len > 1) {
7128             return new ArrayObservable(array, scheduler);
7129         }
7130         else if (len === 1) {
7131             return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7132         }
7133         else {
7134             return new EmptyObservable_1.EmptyObservable(scheduler);
7135         }
7136     };
7137     ArrayObservable.dispatch = function (state) {
7138         var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7139         if (index >= count) {
7140             subscriber.complete();
7141             return;
7142         }
7143         subscriber.next(array[index]);
7144         if (subscriber.closed) {
7145             return;
7146         }
7147         state.index = index + 1;
7148         this.schedule(state);
7149     };
7150     ArrayObservable.prototype._subscribe = function (subscriber) {
7151         var index = 0;
7152         var array = this.array;
7153         var count = array.length;
7154         var scheduler = this.scheduler;
7155         if (scheduler) {
7156             return scheduler.schedule(ArrayObservable.dispatch, 0, {
7157                 array: array, index: index, count: count, subscriber: subscriber
7158             });
7159         }
7160         else {
7161             for (var i = 0; i < count && !subscriber.closed; i++) {
7162                 subscriber.next(array[i]);
7163             }
7164             subscriber.complete();
7165         }
7166     };
7167     return ArrayObservable;
7168 }(Observable_1.Observable));
7169 exports.ArrayObservable = ArrayObservable;
7170
7171 },{"../Observable":29,"../util/isScheduler":175,"./EmptyObservable":91,"./ScalarObservable":97}],89:[function(require,module,exports){
7172 "use strict";
7173 var __extends = (this && this.__extends) || function (d, b) {
7174     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7175     function __() { this.constructor = d; }
7176     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7177 };
7178 var Subject_1 = require('../Subject');
7179 var Observable_1 = require('../Observable');
7180 var Subscriber_1 = require('../Subscriber');
7181 var Subscription_1 = require('../Subscription');
7182 /**
7183  * @class ConnectableObservable<T>
7184  */
7185 var ConnectableObservable = (function (_super) {
7186     __extends(ConnectableObservable, _super);
7187     function ConnectableObservable(source, subjectFactory) {
7188         _super.call(this);
7189         this.source = source;
7190         this.subjectFactory = subjectFactory;
7191         this._refCount = 0;
7192         this._isComplete = false;
7193     }
7194     ConnectableObservable.prototype._subscribe = function (subscriber) {
7195         return this.getSubject().subscribe(subscriber);
7196     };
7197     ConnectableObservable.prototype.getSubject = function () {
7198         var subject = this._subject;
7199         if (!subject || subject.isStopped) {
7200             this._subject = this.subjectFactory();
7201         }
7202         return this._subject;
7203     };
7204     ConnectableObservable.prototype.connect = function () {
7205         var connection = this._connection;
7206         if (!connection) {
7207             this._isComplete = false;
7208             connection = this._connection = new Subscription_1.Subscription();
7209             connection.add(this.source
7210                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7211             if (connection.closed) {
7212                 this._connection = null;
7213                 connection = Subscription_1.Subscription.EMPTY;
7214             }
7215             else {
7216                 this._connection = connection;
7217             }
7218         }
7219         return connection;
7220     };
7221     ConnectableObservable.prototype.refCount = function () {
7222         return this.lift(new RefCountOperator(this));
7223     };
7224     return ConnectableObservable;
7225 }(Observable_1.Observable));
7226 exports.ConnectableObservable = ConnectableObservable;
7227 var connectableProto = ConnectableObservable.prototype;
7228 exports.connectableObservableDescriptor = {
7229     operator: { value: null },
7230     _refCount: { value: 0, writable: true },
7231     _subject: { value: null, writable: true },
7232     _connection: { value: null, writable: true },
7233     _subscribe: { value: connectableProto._subscribe },
7234     _isComplete: { value: connectableProto._isComplete, writable: true },
7235     getSubject: { value: connectableProto.getSubject },
7236     connect: { value: connectableProto.connect },
7237     refCount: { value: connectableProto.refCount }
7238 };
7239 var ConnectableSubscriber = (function (_super) {
7240     __extends(ConnectableSubscriber, _super);
7241     function ConnectableSubscriber(destination, connectable) {
7242         _super.call(this, destination);
7243         this.connectable = connectable;
7244     }
7245     ConnectableSubscriber.prototype._error = function (err) {
7246         this._unsubscribe();
7247         _super.prototype._error.call(this, err);
7248     };
7249     ConnectableSubscriber.prototype._complete = function () {
7250         this.connectable._isComplete = true;
7251         this._unsubscribe();
7252         _super.prototype._complete.call(this);
7253     };
7254     ConnectableSubscriber.prototype._unsubscribe = function () {
7255         var connectable = this.connectable;
7256         if (connectable) {
7257             this.connectable = null;
7258             var connection = connectable._connection;
7259             connectable._refCount = 0;
7260             connectable._subject = null;
7261             connectable._connection = null;
7262             if (connection) {
7263                 connection.unsubscribe();
7264             }
7265         }
7266     };
7267     return ConnectableSubscriber;
7268 }(Subject_1.SubjectSubscriber));
7269 var RefCountOperator = (function () {
7270     function RefCountOperator(connectable) {
7271         this.connectable = connectable;
7272     }
7273     RefCountOperator.prototype.call = function (subscriber, source) {
7274         var connectable = this.connectable;
7275         connectable._refCount++;
7276         var refCounter = new RefCountSubscriber(subscriber, connectable);
7277         var subscription = source.subscribe(refCounter);
7278         if (!refCounter.closed) {
7279             refCounter.connection = connectable.connect();
7280         }
7281         return subscription;
7282     };
7283     return RefCountOperator;
7284 }());
7285 var RefCountSubscriber = (function (_super) {
7286     __extends(RefCountSubscriber, _super);
7287     function RefCountSubscriber(destination, connectable) {
7288         _super.call(this, destination);
7289         this.connectable = connectable;
7290     }
7291     RefCountSubscriber.prototype._unsubscribe = function () {
7292         var connectable = this.connectable;
7293         if (!connectable) {
7294             this.connection = null;
7295             return;
7296         }
7297         this.connectable = null;
7298         var refCount = connectable._refCount;
7299         if (refCount <= 0) {
7300             this.connection = null;
7301             return;
7302         }
7303         connectable._refCount = refCount - 1;
7304         if (refCount > 1) {
7305             this.connection = null;
7306             return;
7307         }
7308         ///
7309         // Compare the local RefCountSubscriber's connection Subscription to the
7310         // connection Subscription on the shared ConnectableObservable. In cases
7311         // where the ConnectableObservable source synchronously emits values, and
7312         // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7313         // execution continues to here before the RefCountOperator has a chance to
7314         // supply the RefCountSubscriber with the shared connection Subscription.
7315         // For example:
7316         // ```
7317         // Observable.range(0, 10)
7318         //   .publish()
7319         //   .refCount()
7320         //   .take(5)
7321         //   .subscribe();
7322         // ```
7323         // In order to account for this case, RefCountSubscriber should only dispose
7324         // the ConnectableObservable's shared connection Subscription if the
7325         // connection Subscription exists, *and* either:
7326         //   a. RefCountSubscriber doesn't have a reference to the shared connection
7327         //      Subscription yet, or,
7328         //   b. RefCountSubscriber's connection Subscription reference is identical
7329         //      to the shared connection Subscription
7330         ///
7331         var connection = this.connection;
7332         var sharedConnection = connectable._connection;
7333         this.connection = null;
7334         if (sharedConnection && (!connection || sharedConnection === connection)) {
7335             sharedConnection.unsubscribe();
7336         }
7337     };
7338     return RefCountSubscriber;
7339 }(Subscriber_1.Subscriber));
7340
7341 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37}],90:[function(require,module,exports){
7342 "use strict";
7343 var __extends = (this && this.__extends) || function (d, b) {
7344     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7345     function __() { this.constructor = d; }
7346     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7347 };
7348 var Observable_1 = require('../Observable');
7349 var subscribeToResult_1 = require('../util/subscribeToResult');
7350 var OuterSubscriber_1 = require('../OuterSubscriber');
7351 /**
7352  * We need this JSDoc comment for affecting ESDoc.
7353  * @extends {Ignored}
7354  * @hide true
7355  */
7356 var DeferObservable = (function (_super) {
7357     __extends(DeferObservable, _super);
7358     function DeferObservable(observableFactory) {
7359         _super.call(this);
7360         this.observableFactory = observableFactory;
7361     }
7362     /**
7363      * Creates an Observable that, on subscribe, calls an Observable factory to
7364      * make an Observable for each new Observer.
7365      *
7366      * <span class="informal">Creates the Observable lazily, that is, only when it
7367      * is subscribed.
7368      * </span>
7369      *
7370      * <img src="./img/defer.png" width="100%">
7371      *
7372      * `defer` allows you to create the Observable only when the Observer
7373      * subscribes, and create a fresh Observable for each Observer. It waits until
7374      * an Observer subscribes to it, and then it generates an Observable,
7375      * typically with an Observable factory function. It does this afresh for each
7376      * subscriber, so although each subscriber may think it is subscribing to the
7377      * same Observable, in fact each subscriber gets its own individual
7378      * Observable.
7379      *
7380      * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7381      * var clicksOrInterval = Rx.Observable.defer(function () {
7382      *   if (Math.random() > 0.5) {
7383      *     return Rx.Observable.fromEvent(document, 'click');
7384      *   } else {
7385      *     return Rx.Observable.interval(1000);
7386      *   }
7387      * });
7388      * clicksOrInterval.subscribe(x => console.log(x));
7389      *
7390      * // Results in the following behavior:
7391      * // If the result of Math.random() is greater than 0.5 it will listen
7392      * // for clicks anywhere on the "document"; when document is clicked it
7393      * // will log a MouseEvent object to the console. If the result is less
7394      * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7395      *
7396      * @see {@link create}
7397      *
7398      * @param {function(): SubscribableOrPromise} observableFactory The Observable
7399      * factory function to invoke for each Observer that subscribes to the output
7400      * Observable. May also return a Promise, which will be converted on the fly
7401      * to an Observable.
7402      * @return {Observable} An Observable whose Observers' subscriptions trigger
7403      * an invocation of the given Observable factory function.
7404      * @static true
7405      * @name defer
7406      * @owner Observable
7407      */
7408     DeferObservable.create = function (observableFactory) {
7409         return new DeferObservable(observableFactory);
7410     };
7411     DeferObservable.prototype._subscribe = function (subscriber) {
7412         return new DeferSubscriber(subscriber, this.observableFactory);
7413     };
7414     return DeferObservable;
7415 }(Observable_1.Observable));
7416 exports.DeferObservable = DeferObservable;
7417 var DeferSubscriber = (function (_super) {
7418     __extends(DeferSubscriber, _super);
7419     function DeferSubscriber(destination, factory) {
7420         _super.call(this, destination);
7421         this.factory = factory;
7422         this.tryDefer();
7423     }
7424     DeferSubscriber.prototype.tryDefer = function () {
7425         try {
7426             this._callFactory();
7427         }
7428         catch (err) {
7429             this._error(err);
7430         }
7431     };
7432     DeferSubscriber.prototype._callFactory = function () {
7433         var result = this.factory();
7434         if (result) {
7435             this.add(subscribeToResult_1.subscribeToResult(this, result));
7436         }
7437     };
7438     return DeferSubscriber;
7439 }(OuterSubscriber_1.OuterSubscriber));
7440
7441 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":177}],91:[function(require,module,exports){
7442 "use strict";
7443 var __extends = (this && this.__extends) || function (d, b) {
7444     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7445     function __() { this.constructor = d; }
7446     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7447 };
7448 var Observable_1 = require('../Observable');
7449 /**
7450  * We need this JSDoc comment for affecting ESDoc.
7451  * @extends {Ignored}
7452  * @hide true
7453  */
7454 var EmptyObservable = (function (_super) {
7455     __extends(EmptyObservable, _super);
7456     function EmptyObservable(scheduler) {
7457         _super.call(this);
7458         this.scheduler = scheduler;
7459     }
7460     /**
7461      * Creates an Observable that emits no items to the Observer and immediately
7462      * emits a complete notification.
7463      *
7464      * <span class="informal">Just emits 'complete', and nothing else.
7465      * </span>
7466      *
7467      * <img src="./img/empty.png" width="100%">
7468      *
7469      * This static operator is useful for creating a simple Observable that only
7470      * emits the complete notification. It can be used for composing with other
7471      * Observables, such as in a {@link mergeMap}.
7472      *
7473      * @example <caption>Emit the number 7, then complete.</caption>
7474      * var result = Rx.Observable.empty().startWith(7);
7475      * result.subscribe(x => console.log(x));
7476      *
7477      * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7478      * var interval = Rx.Observable.interval(1000);
7479      * var result = interval.mergeMap(x =>
7480      *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7481      * );
7482      * result.subscribe(x => console.log(x));
7483      *
7484      * // Results in the following to the console:
7485      * // x is equal to the count on the interval eg(0,1,2,3,...)
7486      * // x will occur every 1000ms
7487      * // if x % 2 is equal to 1 print abc
7488      * // if x % 2 is not equal to 1 nothing will be output
7489      *
7490      * @see {@link create}
7491      * @see {@link never}
7492      * @see {@link of}
7493      * @see {@link throw}
7494      *
7495      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7496      * the emission of the complete notification.
7497      * @return {Observable} An "empty" Observable: emits only the complete
7498      * notification.
7499      * @static true
7500      * @name empty
7501      * @owner Observable
7502      */
7503     EmptyObservable.create = function (scheduler) {
7504         return new EmptyObservable(scheduler);
7505     };
7506     EmptyObservable.dispatch = function (arg) {
7507         var subscriber = arg.subscriber;
7508         subscriber.complete();
7509     };
7510     EmptyObservable.prototype._subscribe = function (subscriber) {
7511         var scheduler = this.scheduler;
7512         if (scheduler) {
7513             return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7514         }
7515         else {
7516             subscriber.complete();
7517         }
7518     };
7519     return EmptyObservable;
7520 }(Observable_1.Observable));
7521 exports.EmptyObservable = EmptyObservable;
7522
7523 },{"../Observable":29}],92:[function(require,module,exports){
7524 "use strict";
7525 var __extends = (this && this.__extends) || function (d, b) {
7526     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7527     function __() { this.constructor = d; }
7528     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7529 };
7530 var Observable_1 = require('../Observable');
7531 /**
7532  * We need this JSDoc comment for affecting ESDoc.
7533  * @extends {Ignored}
7534  * @hide true
7535  */
7536 var ErrorObservable = (function (_super) {
7537     __extends(ErrorObservable, _super);
7538     function ErrorObservable(error, scheduler) {
7539         _super.call(this);
7540         this.error = error;
7541         this.scheduler = scheduler;
7542     }
7543     /**
7544      * Creates an Observable that emits no items to the Observer and immediately
7545      * emits an error notification.
7546      *
7547      * <span class="informal">Just emits 'error', and nothing else.
7548      * </span>
7549      *
7550      * <img src="./img/throw.png" width="100%">
7551      *
7552      * This static operator is useful for creating a simple Observable that only
7553      * emits the error notification. It can be used for composing with other
7554      * Observables, such as in a {@link mergeMap}.
7555      *
7556      * @example <caption>Emit the number 7, then emit an error.</caption>
7557      * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7558      * result.subscribe(x => console.log(x), e => console.error(e));
7559      *
7560      * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7561      * var interval = Rx.Observable.interval(1000);
7562      * var result = interval.mergeMap(x =>
7563      *   x === 13 ?
7564      *     Rx.Observable.throw('Thirteens are bad') :
7565      *     Rx.Observable.of('a', 'b', 'c')
7566      * );
7567      * result.subscribe(x => console.log(x), e => console.error(e));
7568      *
7569      * @see {@link create}
7570      * @see {@link empty}
7571      * @see {@link never}
7572      * @see {@link of}
7573      *
7574      * @param {any} error The particular Error to pass to the error notification.
7575      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7576      * the emission of the error notification.
7577      * @return {Observable} An error Observable: emits only the error notification
7578      * using the given error argument.
7579      * @static true
7580      * @name throw
7581      * @owner Observable
7582      */
7583     ErrorObservable.create = function (error, scheduler) {
7584         return new ErrorObservable(error, scheduler);
7585     };
7586     ErrorObservable.dispatch = function (arg) {
7587         var error = arg.error, subscriber = arg.subscriber;
7588         subscriber.error(error);
7589     };
7590     ErrorObservable.prototype._subscribe = function (subscriber) {
7591         var error = this.error;
7592         var scheduler = this.scheduler;
7593         subscriber.syncErrorThrowable = true;
7594         if (scheduler) {
7595             return scheduler.schedule(ErrorObservable.dispatch, 0, {
7596                 error: error, subscriber: subscriber
7597             });
7598         }
7599         else {
7600             subscriber.error(error);
7601         }
7602     };
7603     return ErrorObservable;
7604 }(Observable_1.Observable));
7605 exports.ErrorObservable = ErrorObservable;
7606
7607 },{"../Observable":29}],93:[function(require,module,exports){
7608 "use strict";
7609 var __extends = (this && this.__extends) || function (d, b) {
7610     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7611     function __() { this.constructor = d; }
7612     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7613 };
7614 var Observable_1 = require('../Observable');
7615 var tryCatch_1 = require('../util/tryCatch');
7616 var isFunction_1 = require('../util/isFunction');
7617 var errorObject_1 = require('../util/errorObject');
7618 var Subscription_1 = require('../Subscription');
7619 var toString = Object.prototype.toString;
7620 function isNodeStyleEventEmitter(sourceObj) {
7621     return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7622 }
7623 function isJQueryStyleEventEmitter(sourceObj) {
7624     return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7625 }
7626 function isNodeList(sourceObj) {
7627     return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7628 }
7629 function isHTMLCollection(sourceObj) {
7630     return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7631 }
7632 function isEventTarget(sourceObj) {
7633     return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7634 }
7635 /**
7636  * We need this JSDoc comment for affecting ESDoc.
7637  * @extends {Ignored}
7638  * @hide true
7639  */
7640 var FromEventObservable = (function (_super) {
7641     __extends(FromEventObservable, _super);
7642     function FromEventObservable(sourceObj, eventName, selector, options) {
7643         _super.call(this);
7644         this.sourceObj = sourceObj;
7645         this.eventName = eventName;
7646         this.selector = selector;
7647         this.options = options;
7648     }
7649     /* tslint:enable:max-line-length */
7650     /**
7651      * Creates an Observable that emits events of a specific type coming from the
7652      * given event target.
7653      *
7654      * <span class="informal">Creates an Observable from DOM events, or Node
7655      * EventEmitter events or others.</span>
7656      *
7657      * <img src="./img/fromEvent.png" width="100%">
7658      *
7659      * Creates an Observable by attaching an event listener to an "event target",
7660      * which may be an object with `addEventListener` and `removeEventListener`,
7661      * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7662      * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7663      * the output Observable is subscribed, and removed when the Subscription is
7664      * unsubscribed.
7665      *
7666      * @example <caption>Emits clicks happening on the DOM document</caption>
7667      * var clicks = Rx.Observable.fromEvent(document, 'click');
7668      * clicks.subscribe(x => console.log(x));
7669      *
7670      * // Results in:
7671      * // MouseEvent object logged to console everytime a click
7672      * // occurs on the document.
7673      *
7674      * @see {@link from}
7675      * @see {@link fromEventPattern}
7676      *
7677      * @param {EventTargetLike} target The DOMElement, event target, Node.js
7678      * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7679      * @param {string} eventName The event name of interest, being emitted by the
7680      * `target`.
7681      * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7682      * @param {SelectorMethodSignature<T>} [selector] An optional function to
7683      * post-process results. It takes the arguments from the event handler and
7684      * should return a single value.
7685      * @return {Observable<T>}
7686      * @static true
7687      * @name fromEvent
7688      * @owner Observable
7689      */
7690     FromEventObservable.create = function (target, eventName, options, selector) {
7691         if (isFunction_1.isFunction(options)) {
7692             selector = options;
7693             options = undefined;
7694         }
7695         return new FromEventObservable(target, eventName, selector, options);
7696     };
7697     FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7698         var unsubscribe;
7699         if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7700             for (var i = 0, len = sourceObj.length; i < len; i++) {
7701                 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7702             }
7703         }
7704         else if (isEventTarget(sourceObj)) {
7705             var source_1 = sourceObj;
7706             sourceObj.addEventListener(eventName, handler, options);
7707             unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7708         }
7709         else if (isJQueryStyleEventEmitter(sourceObj)) {
7710             var source_2 = sourceObj;
7711             sourceObj.on(eventName, handler);
7712             unsubscribe = function () { return source_2.off(eventName, handler); };
7713         }
7714         else if (isNodeStyleEventEmitter(sourceObj)) {
7715             var source_3 = sourceObj;
7716             sourceObj.addListener(eventName, handler);
7717             unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7718         }
7719         else {
7720             throw new TypeError('Invalid event target');
7721         }
7722         subscriber.add(new Subscription_1.Subscription(unsubscribe));
7723     };
7724     FromEventObservable.prototype._subscribe = function (subscriber) {
7725         var sourceObj = this.sourceObj;
7726         var eventName = this.eventName;
7727         var options = this.options;
7728         var selector = this.selector;
7729         var handler = selector ? function () {
7730             var args = [];
7731             for (var _i = 0; _i < arguments.length; _i++) {
7732                 args[_i - 0] = arguments[_i];
7733             }
7734             var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7735             if (result === errorObject_1.errorObject) {
7736                 subscriber.error(errorObject_1.errorObject.e);
7737             }
7738             else {
7739                 subscriber.next(result);
7740             }
7741         } : function (e) { return subscriber.next(e); };
7742         FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7743     };
7744     return FromEventObservable;
7745 }(Observable_1.Observable));
7746 exports.FromEventObservable = FromEventObservable;
7747
7748 },{"../Observable":29,"../Subscription":37,"../util/errorObject":167,"../util/isFunction":171,"../util/tryCatch":179}],94:[function(require,module,exports){
7749 "use strict";
7750 var __extends = (this && this.__extends) || function (d, b) {
7751     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7752     function __() { this.constructor = d; }
7753     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7754 };
7755 var isArray_1 = require('../util/isArray');
7756 var isArrayLike_1 = require('../util/isArrayLike');
7757 var isPromise_1 = require('../util/isPromise');
7758 var PromiseObservable_1 = require('./PromiseObservable');
7759 var IteratorObservable_1 = require('./IteratorObservable');
7760 var ArrayObservable_1 = require('./ArrayObservable');
7761 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7762 var iterator_1 = require('../symbol/iterator');
7763 var Observable_1 = require('../Observable');
7764 var observeOn_1 = require('../operator/observeOn');
7765 var observable_1 = require('../symbol/observable');
7766 /**
7767  * We need this JSDoc comment for affecting ESDoc.
7768  * @extends {Ignored}
7769  * @hide true
7770  */
7771 var FromObservable = (function (_super) {
7772     __extends(FromObservable, _super);
7773     function FromObservable(ish, scheduler) {
7774         _super.call(this, null);
7775         this.ish = ish;
7776         this.scheduler = scheduler;
7777     }
7778     /**
7779      * Creates an Observable from an Array, an array-like object, a Promise, an
7780      * iterable object, or an Observable-like object.
7781      *
7782      * <span class="informal">Converts almost anything to an Observable.</span>
7783      *
7784      * <img src="./img/from.png" width="100%">
7785      *
7786      * Convert various other objects and data types into Observables. `from`
7787      * converts a Promise or an array-like or an
7788      * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7789      * object into an Observable that emits the items in that promise or array or
7790      * iterable. A String, in this context, is treated as an array of characters.
7791      * Observable-like objects (contains a function named with the ES2015 Symbol
7792      * for Observable) can also be converted through this operator.
7793      *
7794      * @example <caption>Converts an array to an Observable</caption>
7795      * var array = [10, 20, 30];
7796      * var result = Rx.Observable.from(array);
7797      * result.subscribe(x => console.log(x));
7798      *
7799      * // Results in the following:
7800      * // 10 20 30
7801      *
7802      * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7803      * function* generateDoubles(seed) {
7804      *   var i = seed;
7805      *   while (true) {
7806      *     yield i;
7807      *     i = 2 * i; // double it
7808      *   }
7809      * }
7810      *
7811      * var iterator = generateDoubles(3);
7812      * var result = Rx.Observable.from(iterator).take(10);
7813      * result.subscribe(x => console.log(x));
7814      *
7815      * // Results in the following:
7816      * // 3 6 12 24 48 96 192 384 768 1536
7817      *
7818      * @see {@link create}
7819      * @see {@link fromEvent}
7820      * @see {@link fromEventPattern}
7821      * @see {@link fromPromise}
7822      *
7823      * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7824      * Observable-like, an Array, an iterable or an array-like object to be
7825      * converted.
7826      * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7827      * emissions of values.
7828      * @return {Observable<T>} The Observable whose values are originally from the
7829      * input object that was converted.
7830      * @static true
7831      * @name from
7832      * @owner Observable
7833      */
7834     FromObservable.create = function (ish, scheduler) {
7835         if (ish != null) {
7836             if (typeof ish[observable_1.observable] === 'function') {
7837                 if (ish instanceof Observable_1.Observable && !scheduler) {
7838                     return ish;
7839                 }
7840                 return new FromObservable(ish, scheduler);
7841             }
7842             else if (isArray_1.isArray(ish)) {
7843                 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7844             }
7845             else if (isPromise_1.isPromise(ish)) {
7846                 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7847             }
7848             else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
7849                 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7850             }
7851             else if (isArrayLike_1.isArrayLike(ish)) {
7852                 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7853             }
7854         }
7855         throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7856     };
7857     FromObservable.prototype._subscribe = function (subscriber) {
7858         var ish = this.ish;
7859         var scheduler = this.scheduler;
7860         if (scheduler == null) {
7861             return ish[observable_1.observable]().subscribe(subscriber);
7862         }
7863         else {
7864             return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7865         }
7866     };
7867     return FromObservable;
7868 }(Observable_1.Observable));
7869 exports.FromObservable = FromObservable;
7870
7871 },{"../Observable":29,"../operator/observeOn":131,"../symbol/iterator":158,"../symbol/observable":159,"../util/isArray":168,"../util/isArrayLike":169,"../util/isPromise":174,"./ArrayLikeObservable":87,"./ArrayObservable":88,"./IteratorObservable":95,"./PromiseObservable":96}],95:[function(require,module,exports){
7872 "use strict";
7873 var __extends = (this && this.__extends) || function (d, b) {
7874     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7875     function __() { this.constructor = d; }
7876     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7877 };
7878 var root_1 = require('../util/root');
7879 var Observable_1 = require('../Observable');
7880 var iterator_1 = require('../symbol/iterator');
7881 /**
7882  * We need this JSDoc comment for affecting ESDoc.
7883  * @extends {Ignored}
7884  * @hide true
7885  */
7886 var IteratorObservable = (function (_super) {
7887     __extends(IteratorObservable, _super);
7888     function IteratorObservable(iterator, scheduler) {
7889         _super.call(this);
7890         this.scheduler = scheduler;
7891         if (iterator == null) {
7892             throw new Error('iterator cannot be null.');
7893         }
7894         this.iterator = getIterator(iterator);
7895     }
7896     IteratorObservable.create = function (iterator, scheduler) {
7897         return new IteratorObservable(iterator, scheduler);
7898     };
7899     IteratorObservable.dispatch = function (state) {
7900         var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7901         if (hasError) {
7902             subscriber.error(state.error);
7903             return;
7904         }
7905         var result = iterator.next();
7906         if (result.done) {
7907             subscriber.complete();
7908             return;
7909         }
7910         subscriber.next(result.value);
7911         state.index = index + 1;
7912         if (subscriber.closed) {
7913             if (typeof iterator.return === 'function') {
7914                 iterator.return();
7915             }
7916             return;
7917         }
7918         this.schedule(state);
7919     };
7920     IteratorObservable.prototype._subscribe = function (subscriber) {
7921         var index = 0;
7922         var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7923         if (scheduler) {
7924             return scheduler.schedule(IteratorObservable.dispatch, 0, {
7925                 index: index, iterator: iterator, subscriber: subscriber
7926             });
7927         }
7928         else {
7929             do {
7930                 var result = iterator.next();
7931                 if (result.done) {
7932                     subscriber.complete();
7933                     break;
7934                 }
7935                 else {
7936                     subscriber.next(result.value);
7937                 }
7938                 if (subscriber.closed) {
7939                     if (typeof iterator.return === 'function') {
7940                         iterator.return();
7941                     }
7942                     break;
7943                 }
7944             } while (true);
7945         }
7946     };
7947     return IteratorObservable;
7948 }(Observable_1.Observable));
7949 exports.IteratorObservable = IteratorObservable;
7950 var StringIterator = (function () {
7951     function StringIterator(str, idx, len) {
7952         if (idx === void 0) { idx = 0; }
7953         if (len === void 0) { len = str.length; }
7954         this.str = str;
7955         this.idx = idx;
7956         this.len = len;
7957     }
7958     StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
7959     StringIterator.prototype.next = function () {
7960         return this.idx < this.len ? {
7961             done: false,
7962             value: this.str.charAt(this.idx++)
7963         } : {
7964             done: true,
7965             value: undefined
7966         };
7967     };
7968     return StringIterator;
7969 }());
7970 var ArrayIterator = (function () {
7971     function ArrayIterator(arr, idx, len) {
7972         if (idx === void 0) { idx = 0; }
7973         if (len === void 0) { len = toLength(arr); }
7974         this.arr = arr;
7975         this.idx = idx;
7976         this.len = len;
7977     }
7978     ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
7979     ArrayIterator.prototype.next = function () {
7980         return this.idx < this.len ? {
7981             done: false,
7982             value: this.arr[this.idx++]
7983         } : {
7984             done: true,
7985             value: undefined
7986         };
7987     };
7988     return ArrayIterator;
7989 }());
7990 function getIterator(obj) {
7991     var i = obj[iterator_1.iterator];
7992     if (!i && typeof obj === 'string') {
7993         return new StringIterator(obj);
7994     }
7995     if (!i && obj.length !== undefined) {
7996         return new ArrayIterator(obj);
7997     }
7998     if (!i) {
7999         throw new TypeError('object is not iterable');
8000     }
8001     return obj[iterator_1.iterator]();
8002 }
8003 var maxSafeInteger = Math.pow(2, 53) - 1;
8004 function toLength(o) {
8005     var len = +o.length;
8006     if (isNaN(len)) {
8007         return 0;
8008     }
8009     if (len === 0 || !numberIsFinite(len)) {
8010         return len;
8011     }
8012     len = sign(len) * Math.floor(Math.abs(len));
8013     if (len <= 0) {
8014         return 0;
8015     }
8016     if (len > maxSafeInteger) {
8017         return maxSafeInteger;
8018     }
8019     return len;
8020 }
8021 function numberIsFinite(value) {
8022     return typeof value === 'number' && root_1.root.isFinite(value);
8023 }
8024 function sign(value) {
8025     var valueAsNumber = +value;
8026     if (valueAsNumber === 0) {
8027         return valueAsNumber;
8028     }
8029     if (isNaN(valueAsNumber)) {
8030         return valueAsNumber;
8031     }
8032     return valueAsNumber < 0 ? -1 : 1;
8033 }
8034
8035 },{"../Observable":29,"../symbol/iterator":158,"../util/root":176}],96:[function(require,module,exports){
8036 "use strict";
8037 var __extends = (this && this.__extends) || function (d, b) {
8038     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8039     function __() { this.constructor = d; }
8040     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8041 };
8042 var root_1 = require('../util/root');
8043 var Observable_1 = require('../Observable');
8044 /**
8045  * We need this JSDoc comment for affecting ESDoc.
8046  * @extends {Ignored}
8047  * @hide true
8048  */
8049 var PromiseObservable = (function (_super) {
8050     __extends(PromiseObservable, _super);
8051     function PromiseObservable(promise, scheduler) {
8052         _super.call(this);
8053         this.promise = promise;
8054         this.scheduler = scheduler;
8055     }
8056     /**
8057      * Converts a Promise to an Observable.
8058      *
8059      * <span class="informal">Returns an Observable that just emits the Promise's
8060      * resolved value, then completes.</span>
8061      *
8062      * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8063      * Observable. If the Promise resolves with a value, the output Observable
8064      * emits that resolved value as a `next`, and then completes. If the Promise
8065      * is rejected, then the output Observable emits the corresponding Error.
8066      *
8067      * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8068      * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8069      * result.subscribe(x => console.log(x), e => console.error(e));
8070      *
8071      * @see {@link bindCallback}
8072      * @see {@link from}
8073      *
8074      * @param {PromiseLike<T>} promise The promise to be converted.
8075      * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8076      * the delivery of the resolved value (or the rejection).
8077      * @return {Observable<T>} An Observable which wraps the Promise.
8078      * @static true
8079      * @name fromPromise
8080      * @owner Observable
8081      */
8082     PromiseObservable.create = function (promise, scheduler) {
8083         return new PromiseObservable(promise, scheduler);
8084     };
8085     PromiseObservable.prototype._subscribe = function (subscriber) {
8086         var _this = this;
8087         var promise = this.promise;
8088         var scheduler = this.scheduler;
8089         if (scheduler == null) {
8090             if (this._isScalar) {
8091                 if (!subscriber.closed) {
8092                     subscriber.next(this.value);
8093                     subscriber.complete();
8094                 }
8095             }
8096             else {
8097                 promise.then(function (value) {
8098                     _this.value = value;
8099                     _this._isScalar = true;
8100                     if (!subscriber.closed) {
8101                         subscriber.next(value);
8102                         subscriber.complete();
8103                     }
8104                 }, function (err) {
8105                     if (!subscriber.closed) {
8106                         subscriber.error(err);
8107                     }
8108                 })
8109                     .then(null, function (err) {
8110                     // escape the promise trap, throw unhandled errors
8111                     root_1.root.setTimeout(function () { throw err; });
8112                 });
8113             }
8114         }
8115         else {
8116             if (this._isScalar) {
8117                 if (!subscriber.closed) {
8118                     return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8119                 }
8120             }
8121             else {
8122                 promise.then(function (value) {
8123                     _this.value = value;
8124                     _this._isScalar = true;
8125                     if (!subscriber.closed) {
8126                         subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8127                     }
8128                 }, function (err) {
8129                     if (!subscriber.closed) {
8130                         subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8131                     }
8132                 })
8133                     .then(null, function (err) {
8134                     // escape the promise trap, throw unhandled errors
8135                     root_1.root.setTimeout(function () { throw err; });
8136                 });
8137             }
8138         }
8139     };
8140     return PromiseObservable;
8141 }(Observable_1.Observable));
8142 exports.PromiseObservable = PromiseObservable;
8143 function dispatchNext(arg) {
8144     var value = arg.value, subscriber = arg.subscriber;
8145     if (!subscriber.closed) {
8146         subscriber.next(value);
8147         subscriber.complete();
8148     }
8149 }
8150 function dispatchError(arg) {
8151     var err = arg.err, subscriber = arg.subscriber;
8152     if (!subscriber.closed) {
8153         subscriber.error(err);
8154     }
8155 }
8156
8157 },{"../Observable":29,"../util/root":176}],97:[function(require,module,exports){
8158 "use strict";
8159 var __extends = (this && this.__extends) || function (d, b) {
8160     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8161     function __() { this.constructor = d; }
8162     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8163 };
8164 var Observable_1 = require('../Observable');
8165 /**
8166  * We need this JSDoc comment for affecting ESDoc.
8167  * @extends {Ignored}
8168  * @hide true
8169  */
8170 var ScalarObservable = (function (_super) {
8171     __extends(ScalarObservable, _super);
8172     function ScalarObservable(value, scheduler) {
8173         _super.call(this);
8174         this.value = value;
8175         this.scheduler = scheduler;
8176         this._isScalar = true;
8177         if (scheduler) {
8178             this._isScalar = false;
8179         }
8180     }
8181     ScalarObservable.create = function (value, scheduler) {
8182         return new ScalarObservable(value, scheduler);
8183     };
8184     ScalarObservable.dispatch = function (state) {
8185         var done = state.done, value = state.value, subscriber = state.subscriber;
8186         if (done) {
8187             subscriber.complete();
8188             return;
8189         }
8190         subscriber.next(value);
8191         if (subscriber.closed) {
8192             return;
8193         }
8194         state.done = true;
8195         this.schedule(state);
8196     };
8197     ScalarObservable.prototype._subscribe = function (subscriber) {
8198         var value = this.value;
8199         var scheduler = this.scheduler;
8200         if (scheduler) {
8201             return scheduler.schedule(ScalarObservable.dispatch, 0, {
8202                 done: false, value: value, subscriber: subscriber
8203             });
8204         }
8205         else {
8206             subscriber.next(value);
8207             if (!subscriber.closed) {
8208                 subscriber.complete();
8209             }
8210         }
8211     };
8212     return ScalarObservable;
8213 }(Observable_1.Observable));
8214 exports.ScalarObservable = ScalarObservable;
8215
8216 },{"../Observable":29}],98:[function(require,module,exports){
8217 "use strict";
8218 var __extends = (this && this.__extends) || function (d, b) {
8219     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8220     function __() { this.constructor = d; }
8221     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8222 };
8223 var isNumeric_1 = require('../util/isNumeric');
8224 var Observable_1 = require('../Observable');
8225 var async_1 = require('../scheduler/async');
8226 var isScheduler_1 = require('../util/isScheduler');
8227 var isDate_1 = require('../util/isDate');
8228 /**
8229  * We need this JSDoc comment for affecting ESDoc.
8230  * @extends {Ignored}
8231  * @hide true
8232  */
8233 var TimerObservable = (function (_super) {
8234     __extends(TimerObservable, _super);
8235     function TimerObservable(dueTime, period, scheduler) {
8236         if (dueTime === void 0) { dueTime = 0; }
8237         _super.call(this);
8238         this.period = -1;
8239         this.dueTime = 0;
8240         if (isNumeric_1.isNumeric(period)) {
8241             this.period = Number(period) < 1 && 1 || Number(period);
8242         }
8243         else if (isScheduler_1.isScheduler(period)) {
8244             scheduler = period;
8245         }
8246         if (!isScheduler_1.isScheduler(scheduler)) {
8247             scheduler = async_1.async;
8248         }
8249         this.scheduler = scheduler;
8250         this.dueTime = isDate_1.isDate(dueTime) ?
8251             (+dueTime - this.scheduler.now()) :
8252             dueTime;
8253     }
8254     /**
8255      * Creates an Observable that starts emitting after an `initialDelay` and
8256      * emits ever increasing numbers after each `period` of time thereafter.
8257      *
8258      * <span class="informal">Its like {@link interval}, but you can specify when
8259      * should the emissions start.</span>
8260      *
8261      * <img src="./img/timer.png" width="100%">
8262      *
8263      * `timer` returns an Observable that emits an infinite sequence of ascending
8264      * integers, with a constant interval of time, `period` of your choosing
8265      * between those emissions. The first emission happens after the specified
8266      * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8267      * operator uses the `async` IScheduler to provide a notion of time, but you
8268      * may pass any IScheduler to it. If `period` is not specified, the output
8269      * Observable emits only one value, `0`. Otherwise, it emits an infinite
8270      * sequence.
8271      *
8272      * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8273      * var numbers = Rx.Observable.timer(3000, 1000);
8274      * numbers.subscribe(x => console.log(x));
8275      *
8276      * @example <caption>Emits one number after five seconds</caption>
8277      * var numbers = Rx.Observable.timer(5000);
8278      * numbers.subscribe(x => console.log(x));
8279      *
8280      * @see {@link interval}
8281      * @see {@link delay}
8282      *
8283      * @param {number|Date} initialDelay The initial delay time to wait before
8284      * emitting the first value of `0`.
8285      * @param {number} [period] The period of time between emissions of the
8286      * subsequent numbers.
8287      * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8288      * the emission of values, and providing a notion of "time".
8289      * @return {Observable} An Observable that emits a `0` after the
8290      * `initialDelay` and ever increasing numbers after each `period` of time
8291      * thereafter.
8292      * @static true
8293      * @name timer
8294      * @owner Observable
8295      */
8296     TimerObservable.create = function (initialDelay, period, scheduler) {
8297         if (initialDelay === void 0) { initialDelay = 0; }
8298         return new TimerObservable(initialDelay, period, scheduler);
8299     };
8300     TimerObservable.dispatch = function (state) {
8301         var index = state.index, period = state.period, subscriber = state.subscriber;
8302         var action = this;
8303         subscriber.next(index);
8304         if (subscriber.closed) {
8305             return;
8306         }
8307         else if (period === -1) {
8308             return subscriber.complete();
8309         }
8310         state.index = index + 1;
8311         action.schedule(state, period);
8312     };
8313     TimerObservable.prototype._subscribe = function (subscriber) {
8314         var index = 0;
8315         var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8316         return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8317             index: index, period: period, subscriber: subscriber
8318         });
8319     };
8320     return TimerObservable;
8321 }(Observable_1.Observable));
8322 exports.TimerObservable = TimerObservable;
8323
8324 },{"../Observable":29,"../scheduler/async":156,"../util/isDate":170,"../util/isNumeric":172,"../util/isScheduler":175}],99:[function(require,module,exports){
8325 "use strict";
8326 var isScheduler_1 = require('../util/isScheduler');
8327 var isArray_1 = require('../util/isArray');
8328 var ArrayObservable_1 = require('./ArrayObservable');
8329 var combineLatest_1 = require('../operator/combineLatest');
8330 /* tslint:enable:max-line-length */
8331 /**
8332  * Combines multiple Observables to create an Observable whose values are
8333  * calculated from the latest values of each of its input Observables.
8334  *
8335  * <span class="informal">Whenever any input Observable emits a value, it
8336  * computes a formula using the latest values from all the inputs, then emits
8337  * the output of that formula.</span>
8338  *
8339  * <img src="./img/combineLatest.png" width="100%">
8340  *
8341  * `combineLatest` combines the values from all the Observables passed as
8342  * arguments. This is done by subscribing to each Observable in order and,
8343  * whenever any Observable emits, collecting an array of the most recent
8344  * values from each Observable. So if you pass `n` Observables to operator,
8345  * returned Observable will always emit an array of `n` values, in order
8346  * corresponding to order of passed Observables (value from the first Observable
8347  * on the first place and so on).
8348  *
8349  * Static version of `combineLatest` accepts either an array of Observables
8350  * or each Observable can be put directly as an argument. Note that array of
8351  * Observables is good choice, if you don't know beforehand how many Observables
8352  * you will combine. Passing empty array will result in Observable that
8353  * completes immediately.
8354  *
8355  * To ensure output array has always the same length, `combineLatest` will
8356  * actually wait for all input Observables to emit at least once,
8357  * before it starts emitting results. This means if some Observable emits
8358  * values before other Observables started emitting, all that values but last
8359  * will be lost. On the other hand, is some Observable does not emit value but
8360  * completes, resulting Observable will complete at the same moment without
8361  * emitting anything, since it will be now impossible to include value from
8362  * completed Observable in resulting array. Also, if some input Observable does
8363  * not emit any value and never completes, `combineLatest` will also never emit
8364  * and never complete, since, again, it will wait for all streams to emit some
8365  * value.
8366  *
8367  * If at least one Observable was passed to `combineLatest` and all passed Observables
8368  * emitted something, resulting Observable will complete when all combined
8369  * streams complete. So even if some Observable completes, result of
8370  * `combineLatest` will still emit values when other Observables do. In case
8371  * of completed Observable, its value from now on will always be the last
8372  * emitted value. On the other hand, if any Observable errors, `combineLatest`
8373  * will error immediately as well, and all other Observables will be unsubscribed.
8374  *
8375  * `combineLatest` accepts as optional parameter `project` function, which takes
8376  * as arguments all values that would normally be emitted by resulting Observable.
8377  * `project` can return any kind of value, which will be then emitted by Observable
8378  * instead of default array. Note that `project` does not take as argument that array
8379  * of values, but values themselves. That means default `project` can be imagined
8380  * as function that takes all its arguments and puts them into an array.
8381  *
8382  *
8383  * @example <caption>Combine two timer Observables</caption>
8384  * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8385  * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8386  * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8387  * combinedTimers.subscribe(value => console.log(value));
8388  * // Logs
8389  * // [0, 0] after 0.5s
8390  * // [1, 0] after 1s
8391  * // [1, 1] after 1.5s
8392  * // [2, 1] after 2s
8393  *
8394  *
8395  * @example <caption>Combine an array of Observables</caption>
8396  * const observables = [1, 5, 10].map(
8397  *   n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8398  * );
8399  * const combined = Rx.Observable.combineLatest(observables);
8400  * combined.subscribe(value => console.log(value));
8401  * // Logs
8402  * // [0, 0, 0] immediately
8403  * // [1, 0, 0] after 1s
8404  * // [1, 5, 0] after 5s
8405  * // [1, 5, 10] after 10s
8406  *
8407  *
8408  * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8409  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8410  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8411  * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8412  * bmi.subscribe(x => console.log('BMI is ' + x));
8413  *
8414  * // With output to console:
8415  * // BMI is 24.212293388429753
8416  * // BMI is 23.93948099205209
8417  * // BMI is 23.671253629592222
8418  *
8419  *
8420  * @see {@link combineAll}
8421  * @see {@link merge}
8422  * @see {@link withLatestFrom}
8423  *
8424  * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8425  * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8426  * More than one input Observables may be given as arguments
8427  * or an array of Observables may be given as the first argument.
8428  * @param {function} [project] An optional function to project the values from
8429  * the combined latest values into a new value on the output Observable.
8430  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8431  * each input Observable.
8432  * @return {Observable} An Observable of projected values from the most recent
8433  * values from each input Observable, or an array of the most recent values from
8434  * each input Observable.
8435  * @static true
8436  * @name combineLatest
8437  * @owner Observable
8438  */
8439 function combineLatest() {
8440     var observables = [];
8441     for (var _i = 0; _i < arguments.length; _i++) {
8442         observables[_i - 0] = arguments[_i];
8443     }
8444     var project = null;
8445     var scheduler = null;
8446     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8447         scheduler = observables.pop();
8448     }
8449     if (typeof observables[observables.length - 1] === 'function') {
8450         project = observables.pop();
8451     }
8452     // if the first and only other argument besides the resultSelector is an array
8453     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8454     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8455         observables = observables[0];
8456     }
8457     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8458 }
8459 exports.combineLatest = combineLatest;
8460
8461 },{"../operator/combineLatest":114,"../util/isArray":168,"../util/isScheduler":175,"./ArrayObservable":88}],100:[function(require,module,exports){
8462 "use strict";
8463 var DeferObservable_1 = require('./DeferObservable');
8464 exports.defer = DeferObservable_1.DeferObservable.create;
8465
8466 },{"./DeferObservable":90}],101:[function(require,module,exports){
8467 "use strict";
8468 var EmptyObservable_1 = require('./EmptyObservable');
8469 exports.empty = EmptyObservable_1.EmptyObservable.create;
8470
8471 },{"./EmptyObservable":91}],102:[function(require,module,exports){
8472 "use strict";
8473 var FromObservable_1 = require('./FromObservable');
8474 exports.from = FromObservable_1.FromObservable.create;
8475
8476 },{"./FromObservable":94}],103:[function(require,module,exports){
8477 "use strict";
8478 var FromEventObservable_1 = require('./FromEventObservable');
8479 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8480
8481 },{"./FromEventObservable":93}],104:[function(require,module,exports){
8482 "use strict";
8483 var PromiseObservable_1 = require('./PromiseObservable');
8484 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8485
8486 },{"./PromiseObservable":96}],105:[function(require,module,exports){
8487 "use strict";
8488 var merge_1 = require('../operator/merge');
8489 exports.merge = merge_1.mergeStatic;
8490
8491 },{"../operator/merge":127}],106:[function(require,module,exports){
8492 "use strict";
8493 var ArrayObservable_1 = require('./ArrayObservable');
8494 exports.of = ArrayObservable_1.ArrayObservable.of;
8495
8496 },{"./ArrayObservable":88}],107:[function(require,module,exports){
8497 "use strict";
8498 var ErrorObservable_1 = require('./ErrorObservable');
8499 exports._throw = ErrorObservable_1.ErrorObservable.create;
8500
8501 },{"./ErrorObservable":92}],108:[function(require,module,exports){
8502 "use strict";
8503 var TimerObservable_1 = require('./TimerObservable');
8504 exports.timer = TimerObservable_1.TimerObservable.create;
8505
8506 },{"./TimerObservable":98}],109:[function(require,module,exports){
8507 "use strict";
8508 var zip_1 = require('../operator/zip');
8509 exports.zip = zip_1.zipStatic;
8510
8511 },{"../operator/zip":150}],110:[function(require,module,exports){
8512 "use strict";
8513 var __extends = (this && this.__extends) || function (d, b) {
8514     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8515     function __() { this.constructor = d; }
8516     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8517 };
8518 var OuterSubscriber_1 = require('../OuterSubscriber');
8519 var subscribeToResult_1 = require('../util/subscribeToResult');
8520 /**
8521  * Buffers the source Observable values until `closingNotifier` emits.
8522  *
8523  * <span class="informal">Collects values from the past as an array, and emits
8524  * that array only when another Observable emits.</span>
8525  *
8526  * <img src="./img/buffer.png" width="100%">
8527  *
8528  * Buffers the incoming Observable values until the given `closingNotifier`
8529  * Observable emits a value, at which point it emits the buffer on the output
8530  * Observable and starts a new buffer internally, awaiting the next time
8531  * `closingNotifier` emits.
8532  *
8533  * @example <caption>On every click, emit array of most recent interval events</caption>
8534  * var clicks = Rx.Observable.fromEvent(document, 'click');
8535  * var interval = Rx.Observable.interval(1000);
8536  * var buffered = interval.buffer(clicks);
8537  * buffered.subscribe(x => console.log(x));
8538  *
8539  * @see {@link bufferCount}
8540  * @see {@link bufferTime}
8541  * @see {@link bufferToggle}
8542  * @see {@link bufferWhen}
8543  * @see {@link window}
8544  *
8545  * @param {Observable<any>} closingNotifier An Observable that signals the
8546  * buffer to be emitted on the output Observable.
8547  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8548  * values.
8549  * @method buffer
8550  * @owner Observable
8551  */
8552 function buffer(closingNotifier) {
8553     return this.lift(new BufferOperator(closingNotifier));
8554 }
8555 exports.buffer = buffer;
8556 var BufferOperator = (function () {
8557     function BufferOperator(closingNotifier) {
8558         this.closingNotifier = closingNotifier;
8559     }
8560     BufferOperator.prototype.call = function (subscriber, source) {
8561         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8562     };
8563     return BufferOperator;
8564 }());
8565 /**
8566  * We need this JSDoc comment for affecting ESDoc.
8567  * @ignore
8568  * @extends {Ignored}
8569  */
8570 var BufferSubscriber = (function (_super) {
8571     __extends(BufferSubscriber, _super);
8572     function BufferSubscriber(destination, closingNotifier) {
8573         _super.call(this, destination);
8574         this.buffer = [];
8575         this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8576     }
8577     BufferSubscriber.prototype._next = function (value) {
8578         this.buffer.push(value);
8579     };
8580     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8581         var buffer = this.buffer;
8582         this.buffer = [];
8583         this.destination.next(buffer);
8584     };
8585     return BufferSubscriber;
8586 }(OuterSubscriber_1.OuterSubscriber));
8587
8588 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],111:[function(require,module,exports){
8589 "use strict";
8590 var __extends = (this && this.__extends) || function (d, b) {
8591     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8592     function __() { this.constructor = d; }
8593     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8594 };
8595 var Subscriber_1 = require('../Subscriber');
8596 /**
8597  * Buffers the source Observable values until the size hits the maximum
8598  * `bufferSize` given.
8599  *
8600  * <span class="informal">Collects values from the past as an array, and emits
8601  * that array only when its size reaches `bufferSize`.</span>
8602  *
8603  * <img src="./img/bufferCount.png" width="100%">
8604  *
8605  * Buffers a number of values from the source Observable by `bufferSize` then
8606  * emits the buffer and clears it, and starts a new buffer each
8607  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8608  * `null`, then new buffers are started immediately at the start of the source
8609  * and when each buffer closes and is emitted.
8610  *
8611  * @example <caption>Emit the last two click events as an array</caption>
8612  * var clicks = Rx.Observable.fromEvent(document, 'click');
8613  * var buffered = clicks.bufferCount(2);
8614  * buffered.subscribe(x => console.log(x));
8615  *
8616  * @example <caption>On every click, emit the last two click events as an array</caption>
8617  * var clicks = Rx.Observable.fromEvent(document, 'click');
8618  * var buffered = clicks.bufferCount(2, 1);
8619  * buffered.subscribe(x => console.log(x));
8620  *
8621  * @see {@link buffer}
8622  * @see {@link bufferTime}
8623  * @see {@link bufferToggle}
8624  * @see {@link bufferWhen}
8625  * @see {@link pairwise}
8626  * @see {@link windowCount}
8627  *
8628  * @param {number} bufferSize The maximum size of the buffer emitted.
8629  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8630  * For example if `startBufferEvery` is `2`, then a new buffer will be started
8631  * on every other value from the source. A new buffer is started at the
8632  * beginning of the source by default.
8633  * @return {Observable<T[]>} An Observable of arrays of buffered values.
8634  * @method bufferCount
8635  * @owner Observable
8636  */
8637 function bufferCount(bufferSize, startBufferEvery) {
8638     if (startBufferEvery === void 0) { startBufferEvery = null; }
8639     return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8640 }
8641 exports.bufferCount = bufferCount;
8642 var BufferCountOperator = (function () {
8643     function BufferCountOperator(bufferSize, startBufferEvery) {
8644         this.bufferSize = bufferSize;
8645         this.startBufferEvery = startBufferEvery;
8646         if (!startBufferEvery || bufferSize === startBufferEvery) {
8647             this.subscriberClass = BufferCountSubscriber;
8648         }
8649         else {
8650             this.subscriberClass = BufferSkipCountSubscriber;
8651         }
8652     }
8653     BufferCountOperator.prototype.call = function (subscriber, source) {
8654         return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
8655     };
8656     return BufferCountOperator;
8657 }());
8658 /**
8659  * We need this JSDoc comment for affecting ESDoc.
8660  * @ignore
8661  * @extends {Ignored}
8662  */
8663 var BufferCountSubscriber = (function (_super) {
8664     __extends(BufferCountSubscriber, _super);
8665     function BufferCountSubscriber(destination, bufferSize) {
8666         _super.call(this, destination);
8667         this.bufferSize = bufferSize;
8668         this.buffer = [];
8669     }
8670     BufferCountSubscriber.prototype._next = function (value) {
8671         var buffer = this.buffer;
8672         buffer.push(value);
8673         if (buffer.length == this.bufferSize) {
8674             this.destination.next(buffer);
8675             this.buffer = [];
8676         }
8677     };
8678     BufferCountSubscriber.prototype._complete = function () {
8679         var buffer = this.buffer;
8680         if (buffer.length > 0) {
8681             this.destination.next(buffer);
8682         }
8683         _super.prototype._complete.call(this);
8684     };
8685     return BufferCountSubscriber;
8686 }(Subscriber_1.Subscriber));
8687 /**
8688  * We need this JSDoc comment for affecting ESDoc.
8689  * @ignore
8690  * @extends {Ignored}
8691  */
8692 var BufferSkipCountSubscriber = (function (_super) {
8693     __extends(BufferSkipCountSubscriber, _super);
8694     function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
8695         _super.call(this, destination);
8696         this.bufferSize = bufferSize;
8697         this.startBufferEvery = startBufferEvery;
8698         this.buffers = [];
8699         this.count = 0;
8700     }
8701     BufferSkipCountSubscriber.prototype._next = function (value) {
8702         var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
8703         this.count++;
8704         if (count % startBufferEvery === 0) {
8705             buffers.push([]);
8706         }
8707         for (var i = buffers.length; i--;) {
8708             var buffer = buffers[i];
8709             buffer.push(value);
8710             if (buffer.length === bufferSize) {
8711                 buffers.splice(i, 1);
8712                 this.destination.next(buffer);
8713             }
8714         }
8715     };
8716     BufferSkipCountSubscriber.prototype._complete = function () {
8717         var _a = this, buffers = _a.buffers, destination = _a.destination;
8718         while (buffers.length > 0) {
8719             var buffer = buffers.shift();
8720             if (buffer.length > 0) {
8721                 destination.next(buffer);
8722             }
8723         }
8724         _super.prototype._complete.call(this);
8725     };
8726     return BufferSkipCountSubscriber;
8727 }(Subscriber_1.Subscriber));
8728
8729 },{"../Subscriber":36}],112:[function(require,module,exports){
8730 "use strict";
8731 var __extends = (this && this.__extends) || function (d, b) {
8732     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8733     function __() { this.constructor = d; }
8734     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8735 };
8736 var Subscription_1 = require('../Subscription');
8737 var tryCatch_1 = require('../util/tryCatch');
8738 var errorObject_1 = require('../util/errorObject');
8739 var OuterSubscriber_1 = require('../OuterSubscriber');
8740 var subscribeToResult_1 = require('../util/subscribeToResult');
8741 /**
8742  * Buffers the source Observable values, using a factory function of closing
8743  * Observables to determine when to close, emit, and reset the buffer.
8744  *
8745  * <span class="informal">Collects values from the past as an array. When it
8746  * starts collecting values, it calls a function that returns an Observable that
8747  * tells when to close the buffer and restart collecting.</span>
8748  *
8749  * <img src="./img/bufferWhen.png" width="100%">
8750  *
8751  * Opens a buffer immediately, then closes the buffer when the observable
8752  * returned by calling `closingSelector` function emits a value. When it closes
8753  * the buffer, it immediately opens a new buffer and repeats the process.
8754  *
8755  * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8756  * var clicks = Rx.Observable.fromEvent(document, 'click');
8757  * var buffered = clicks.bufferWhen(() =>
8758  *   Rx.Observable.interval(1000 + Math.random() * 4000)
8759  * );
8760  * buffered.subscribe(x => console.log(x));
8761  *
8762  * @see {@link buffer}
8763  * @see {@link bufferCount}
8764  * @see {@link bufferTime}
8765  * @see {@link bufferToggle}
8766  * @see {@link windowWhen}
8767  *
8768  * @param {function(): Observable} closingSelector A function that takes no
8769  * arguments and returns an Observable that signals buffer closure.
8770  * @return {Observable<T[]>} An observable of arrays of buffered values.
8771  * @method bufferWhen
8772  * @owner Observable
8773  */
8774 function bufferWhen(closingSelector) {
8775     return this.lift(new BufferWhenOperator(closingSelector));
8776 }
8777 exports.bufferWhen = bufferWhen;
8778 var BufferWhenOperator = (function () {
8779     function BufferWhenOperator(closingSelector) {
8780         this.closingSelector = closingSelector;
8781     }
8782     BufferWhenOperator.prototype.call = function (subscriber, source) {
8783         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8784     };
8785     return BufferWhenOperator;
8786 }());
8787 /**
8788  * We need this JSDoc comment for affecting ESDoc.
8789  * @ignore
8790  * @extends {Ignored}
8791  */
8792 var BufferWhenSubscriber = (function (_super) {
8793     __extends(BufferWhenSubscriber, _super);
8794     function BufferWhenSubscriber(destination, closingSelector) {
8795         _super.call(this, destination);
8796         this.closingSelector = closingSelector;
8797         this.subscribing = false;
8798         this.openBuffer();
8799     }
8800     BufferWhenSubscriber.prototype._next = function (value) {
8801         this.buffer.push(value);
8802     };
8803     BufferWhenSubscriber.prototype._complete = function () {
8804         var buffer = this.buffer;
8805         if (buffer) {
8806             this.destination.next(buffer);
8807         }
8808         _super.prototype._complete.call(this);
8809     };
8810     BufferWhenSubscriber.prototype._unsubscribe = function () {
8811         this.buffer = null;
8812         this.subscribing = false;
8813     };
8814     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8815         this.openBuffer();
8816     };
8817     BufferWhenSubscriber.prototype.notifyComplete = function () {
8818         if (this.subscribing) {
8819             this.complete();
8820         }
8821         else {
8822             this.openBuffer();
8823         }
8824     };
8825     BufferWhenSubscriber.prototype.openBuffer = function () {
8826         var closingSubscription = this.closingSubscription;
8827         if (closingSubscription) {
8828             this.remove(closingSubscription);
8829             closingSubscription.unsubscribe();
8830         }
8831         var buffer = this.buffer;
8832         if (this.buffer) {
8833             this.destination.next(buffer);
8834         }
8835         this.buffer = [];
8836         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
8837         if (closingNotifier === errorObject_1.errorObject) {
8838             this.error(errorObject_1.errorObject.e);
8839         }
8840         else {
8841             closingSubscription = new Subscription_1.Subscription();
8842             this.closingSubscription = closingSubscription;
8843             this.add(closingSubscription);
8844             this.subscribing = true;
8845             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8846             this.subscribing = false;
8847         }
8848     };
8849     return BufferWhenSubscriber;
8850 }(OuterSubscriber_1.OuterSubscriber));
8851
8852 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":167,"../util/subscribeToResult":177,"../util/tryCatch":179}],113:[function(require,module,exports){
8853 "use strict";
8854 var __extends = (this && this.__extends) || function (d, b) {
8855     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8856     function __() { this.constructor = d; }
8857     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8858 };
8859 var OuterSubscriber_1 = require('../OuterSubscriber');
8860 var subscribeToResult_1 = require('../util/subscribeToResult');
8861 /**
8862  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8863  *
8864  * <img src="./img/catch.png" width="100%">
8865  *
8866  * @example <caption>Continues with a different Observable when there's an error</caption>
8867  *
8868  * Observable.of(1, 2, 3, 4, 5)
8869  *   .map(n => {
8870  *         if (n == 4) {
8871  *           throw 'four!';
8872  *     }
8873  *         return n;
8874  *   })
8875  *   .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8876  *   .subscribe(x => console.log(x));
8877  *   // 1, 2, 3, I, II, III, IV, V
8878  *
8879  * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8880  *
8881  * Observable.of(1, 2, 3, 4, 5)
8882  *   .map(n => {
8883  *         if (n === 4) {
8884  *           throw 'four!';
8885  *     }
8886  *         return n;
8887  *   })
8888  *   .catch((err, caught) => caught)
8889  *   .take(30)
8890  *   .subscribe(x => console.log(x));
8891  *   // 1, 2, 3, 1, 2, 3, ...
8892  *
8893  * @example <caption>Throws a new error when the source Observable throws an error</caption>
8894  *
8895  * Observable.of(1, 2, 3, 4, 5)
8896  *   .map(n => {
8897  *     if (n == 4) {
8898  *       throw 'four!';
8899  *     }
8900  *     return n;
8901  *   })
8902  *   .catch(err => {
8903  *     throw 'error in source. Details: ' + err;
8904  *   })
8905  *   .subscribe(
8906  *     x => console.log(x),
8907  *     err => console.log(err)
8908  *   );
8909  *   // 1, 2, 3, error in source. Details: four!
8910  *
8911  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8912  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8913  *  is returned by the `selector` will be used to continue the observable chain.
8914  * @return {Observable} An observable that originates from either the source or the observable returned by the
8915  *  catch `selector` function.
8916  * @method catch
8917  * @name catch
8918  * @owner Observable
8919  */
8920 function _catch(selector) {
8921     var operator = new CatchOperator(selector);
8922     var caught = this.lift(operator);
8923     return (operator.caught = caught);
8924 }
8925 exports._catch = _catch;
8926 var CatchOperator = (function () {
8927     function CatchOperator(selector) {
8928         this.selector = selector;
8929     }
8930     CatchOperator.prototype.call = function (subscriber, source) {
8931         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8932     };
8933     return CatchOperator;
8934 }());
8935 /**
8936  * We need this JSDoc comment for affecting ESDoc.
8937  * @ignore
8938  * @extends {Ignored}
8939  */
8940 var CatchSubscriber = (function (_super) {
8941     __extends(CatchSubscriber, _super);
8942     function CatchSubscriber(destination, selector, caught) {
8943         _super.call(this, destination);
8944         this.selector = selector;
8945         this.caught = caught;
8946     }
8947     // NOTE: overriding `error` instead of `_error` because we don't want
8948     // to have this flag this subscriber as `isStopped`. We can mimic the
8949     // behavior of the RetrySubscriber (from the `retry` operator), where
8950     // we unsubscribe from our source chain, reset our Subscriber flags,
8951     // then subscribe to the selector result.
8952     CatchSubscriber.prototype.error = function (err) {
8953         if (!this.isStopped) {
8954             var result = void 0;
8955             try {
8956                 result = this.selector(err, this.caught);
8957             }
8958             catch (err2) {
8959                 _super.prototype.error.call(this, err2);
8960                 return;
8961             }
8962             this._unsubscribeAndRecycle();
8963             this.add(subscribeToResult_1.subscribeToResult(this, result));
8964         }
8965     };
8966     return CatchSubscriber;
8967 }(OuterSubscriber_1.OuterSubscriber));
8968
8969 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],114:[function(require,module,exports){
8970 "use strict";
8971 var __extends = (this && this.__extends) || function (d, b) {
8972     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8973     function __() { this.constructor = d; }
8974     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8975 };
8976 var ArrayObservable_1 = require('../observable/ArrayObservable');
8977 var isArray_1 = require('../util/isArray');
8978 var OuterSubscriber_1 = require('../OuterSubscriber');
8979 var subscribeToResult_1 = require('../util/subscribeToResult');
8980 var none = {};
8981 /* tslint:enable:max-line-length */
8982 /**
8983  * Combines multiple Observables to create an Observable whose values are
8984  * calculated from the latest values of each of its input Observables.
8985  *
8986  * <span class="informal">Whenever any input Observable emits a value, it
8987  * computes a formula using the latest values from all the inputs, then emits
8988  * the output of that formula.</span>
8989  *
8990  * <img src="./img/combineLatest.png" width="100%">
8991  *
8992  * `combineLatest` combines the values from this Observable with values from
8993  * Observables passed as arguments. This is done by subscribing to each
8994  * Observable, in order, and collecting an array of each of the most recent
8995  * values any time any of the input Observables emits, then either taking that
8996  * array and passing it as arguments to an optional `project` function and
8997  * emitting the return value of that, or just emitting the array of recent
8998  * values directly if there is no `project` function.
8999  *
9000  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
9001  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
9002  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
9003  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
9004  * bmi.subscribe(x => console.log('BMI is ' + x));
9005  *
9006  * // With output to console:
9007  * // BMI is 24.212293388429753
9008  * // BMI is 23.93948099205209
9009  * // BMI is 23.671253629592222
9010  *
9011  * @see {@link combineAll}
9012  * @see {@link merge}
9013  * @see {@link withLatestFrom}
9014  *
9015  * @param {ObservableInput} other An input Observable to combine with the source
9016  * Observable. More than one input Observables may be given as argument.
9017  * @param {function} [project] An optional function to project the values from
9018  * the combined latest values into a new value on the output Observable.
9019  * @return {Observable} An Observable of projected values from the most recent
9020  * values from each input Observable, or an array of the most recent values from
9021  * each input Observable.
9022  * @method combineLatest
9023  * @owner Observable
9024  */
9025 function combineLatest() {
9026     var observables = [];
9027     for (var _i = 0; _i < arguments.length; _i++) {
9028         observables[_i - 0] = arguments[_i];
9029     }
9030     var project = null;
9031     if (typeof observables[observables.length - 1] === 'function') {
9032         project = observables.pop();
9033     }
9034     // if the first and only other argument besides the resultSelector is an array
9035     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
9036     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
9037         observables = observables[0].slice();
9038     }
9039     observables.unshift(this);
9040     return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
9041 }
9042 exports.combineLatest = combineLatest;
9043 var CombineLatestOperator = (function () {
9044     function CombineLatestOperator(project) {
9045         this.project = project;
9046     }
9047     CombineLatestOperator.prototype.call = function (subscriber, source) {
9048         return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
9049     };
9050     return CombineLatestOperator;
9051 }());
9052 exports.CombineLatestOperator = CombineLatestOperator;
9053 /**
9054  * We need this JSDoc comment for affecting ESDoc.
9055  * @ignore
9056  * @extends {Ignored}
9057  */
9058 var CombineLatestSubscriber = (function (_super) {
9059     __extends(CombineLatestSubscriber, _super);
9060     function CombineLatestSubscriber(destination, project) {
9061         _super.call(this, destination);
9062         this.project = project;
9063         this.active = 0;
9064         this.values = [];
9065         this.observables = [];
9066     }
9067     CombineLatestSubscriber.prototype._next = function (observable) {
9068         this.values.push(none);
9069         this.observables.push(observable);
9070     };
9071     CombineLatestSubscriber.prototype._complete = function () {
9072         var observables = this.observables;
9073         var len = observables.length;
9074         if (len === 0) {
9075             this.destination.complete();
9076         }
9077         else {
9078             this.active = len;
9079             this.toRespond = len;
9080             for (var i = 0; i < len; i++) {
9081                 var observable = observables[i];
9082                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
9083             }
9084         }
9085     };
9086     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
9087         if ((this.active -= 1) === 0) {
9088             this.destination.complete();
9089         }
9090     };
9091     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9092         var values = this.values;
9093         var oldVal = values[outerIndex];
9094         var toRespond = !this.toRespond
9095             ? 0
9096             : oldVal === none ? --this.toRespond : this.toRespond;
9097         values[outerIndex] = innerValue;
9098         if (toRespond === 0) {
9099             if (this.project) {
9100                 this._tryProject(values);
9101             }
9102             else {
9103                 this.destination.next(values.slice());
9104             }
9105         }
9106     };
9107     CombineLatestSubscriber.prototype._tryProject = function (values) {
9108         var result;
9109         try {
9110             result = this.project.apply(this, values);
9111         }
9112         catch (err) {
9113             this.destination.error(err);
9114             return;
9115         }
9116         this.destination.next(result);
9117     };
9118     return CombineLatestSubscriber;
9119 }(OuterSubscriber_1.OuterSubscriber));
9120 exports.CombineLatestSubscriber = CombineLatestSubscriber;
9121
9122 },{"../OuterSubscriber":31,"../observable/ArrayObservable":88,"../util/isArray":168,"../util/subscribeToResult":177}],115:[function(require,module,exports){
9123 "use strict";
9124 var Observable_1 = require('../Observable');
9125 var isScheduler_1 = require('../util/isScheduler');
9126 var ArrayObservable_1 = require('../observable/ArrayObservable');
9127 var mergeAll_1 = require('./mergeAll');
9128 /* tslint:enable:max-line-length */
9129 /**
9130  * Creates an output Observable which sequentially emits all values from every
9131  * given input Observable after the current Observable.
9132  *
9133  * <span class="informal">Concatenates multiple Observables together by
9134  * sequentially emitting their values, one Observable after the other.</span>
9135  *
9136  * <img src="./img/concat.png" width="100%">
9137  *
9138  * Joins this Observable with multiple other Observables by subscribing to them
9139  * one at a time, starting with the source, and merging their results into the
9140  * output Observable. Will wait for each Observable to complete before moving
9141  * on to the next.
9142  *
9143  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9144  * var timer = Rx.Observable.interval(1000).take(4);
9145  * var sequence = Rx.Observable.range(1, 10);
9146  * var result = timer.concat(sequence);
9147  * result.subscribe(x => console.log(x));
9148  *
9149  * // results in:
9150  * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9151  *
9152  * @example <caption>Concatenate 3 Observables</caption>
9153  * var timer1 = Rx.Observable.interval(1000).take(10);
9154  * var timer2 = Rx.Observable.interval(2000).take(6);
9155  * var timer3 = Rx.Observable.interval(500).take(10);
9156  * var result = timer1.concat(timer2, timer3);
9157  * result.subscribe(x => console.log(x));
9158  *
9159  * // results in the following:
9160  * // (Prints to console sequentially)
9161  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9162  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9163  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9164  *
9165  * @see {@link concatAll}
9166  * @see {@link concatMap}
9167  * @see {@link concatMapTo}
9168  *
9169  * @param {ObservableInput} other An input Observable to concatenate after the source
9170  * Observable. More than one input Observables may be given as argument.
9171  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9172  * Observable subscription on.
9173  * @return {Observable} All values of each passed Observable merged into a
9174  * single Observable, in order, in serial fashion.
9175  * @method concat
9176  * @owner Observable
9177  */
9178 function concat() {
9179     var observables = [];
9180     for (var _i = 0; _i < arguments.length; _i++) {
9181         observables[_i - 0] = arguments[_i];
9182     }
9183     return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
9184 }
9185 exports.concat = concat;
9186 /* tslint:enable:max-line-length */
9187 /**
9188  * Creates an output Observable which sequentially emits all values from given
9189  * Observable and then moves on to the next.
9190  *
9191  * <span class="informal">Concatenates multiple Observables together by
9192  * sequentially emitting their values, one Observable after the other.</span>
9193  *
9194  * <img src="./img/concat.png" width="100%">
9195  *
9196  * `concat` joins multiple Observables together, by subscribing to them one at a time and
9197  * merging their results into the output Observable. You can pass either an array of
9198  * Observables, or put them directly as arguments. Passing an empty array will result
9199  * in Observable that completes immediately.
9200  *
9201  * `concat` will subscribe to first input Observable and emit all its values, without
9202  * changing or affecting them in any way. When that Observable completes, it will
9203  * subscribe to then next Observable passed and, again, emit its values. This will be
9204  * repeated, until the operator runs out of Observables. When last input Observable completes,
9205  * `concat` will complete as well. At any given moment only one Observable passed to operator
9206  * emits values. If you would like to emit values from passed Observables concurrently, check out
9207  * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
9208  * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
9209  *
9210  * Note that if some input Observable never completes, `concat` will also never complete
9211  * and Observables following the one that did not complete will never be subscribed. On the other
9212  * hand, if some Observable simply completes immediately after it is subscribed, it will be
9213  * invisible for `concat`, which will just move on to the next Observable.
9214  *
9215  * If any Observable in chain errors, instead of passing control to the next Observable,
9216  * `concat` will error immediately as well. Observables that would be subscribed after
9217  * the one that emitted error, never will.
9218  *
9219  * If you pass to `concat` the same Observable many times, its stream of values
9220  * will be "replayed" on every subscription, which means you can repeat given Observable
9221  * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
9222  * you can always use {@link repeat}.
9223  *
9224  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9225  * var timer = Rx.Observable.interval(1000).take(4);
9226  * var sequence = Rx.Observable.range(1, 10);
9227  * var result = Rx.Observable.concat(timer, sequence);
9228  * result.subscribe(x => console.log(x));
9229  *
9230  * // results in:
9231  * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9232  *
9233  *
9234  * @example <caption>Concatenate an array of 3 Observables</caption>
9235  * var timer1 = Rx.Observable.interval(1000).take(10);
9236  * var timer2 = Rx.Observable.interval(2000).take(6);
9237  * var timer3 = Rx.Observable.interval(500).take(10);
9238  * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
9239  * result.subscribe(x => console.log(x));
9240  *
9241  * // results in the following:
9242  * // (Prints to console sequentially)
9243  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9244  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9245  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9246  *
9247  *
9248  * @example <caption>Concatenate the same Observable to repeat it</caption>
9249  * const timer = Rx.Observable.interval(1000).take(2);
9250  *
9251  * Rx.Observable.concat(timer, timer) // concating the same Observable!
9252  * .subscribe(
9253  *   value => console.log(value),
9254  *   err => {},
9255  *   () => console.log('...and it is done!')
9256  * );
9257  *
9258  * // Logs:
9259  * // 0 after 1s
9260  * // 1 after 2s
9261  * // 0 after 3s
9262  * // 1 after 4s
9263  * // "...and it is done!" also after 4s
9264  *
9265  * @see {@link concatAll}
9266  * @see {@link concatMap}
9267  * @see {@link concatMapTo}
9268  *
9269  * @param {ObservableInput} input1 An input Observable to concatenate with others.
9270  * @param {ObservableInput} input2 An input Observable to concatenate with others.
9271  * More than one input Observables may be given as argument.
9272  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9273  * Observable subscription on.
9274  * @return {Observable} All values of each passed Observable merged into a
9275  * single Observable, in order, in serial fashion.
9276  * @static true
9277  * @name concat
9278  * @owner Observable
9279  */
9280 function concatStatic() {
9281     var observables = [];
9282     for (var _i = 0; _i < arguments.length; _i++) {
9283         observables[_i - 0] = arguments[_i];
9284     }
9285     var scheduler = null;
9286     var args = observables;
9287     if (isScheduler_1.isScheduler(args[observables.length - 1])) {
9288         scheduler = args.pop();
9289     }
9290     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
9291         return observables[0];
9292     }
9293     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
9294 }
9295 exports.concatStatic = concatStatic;
9296
9297 },{"../Observable":29,"../observable/ArrayObservable":88,"../util/isScheduler":175,"./mergeAll":128}],116:[function(require,module,exports){
9298 "use strict";
9299 var __extends = (this && this.__extends) || function (d, b) {
9300     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9301     function __() { this.constructor = d; }
9302     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9303 };
9304 var Subscriber_1 = require('../Subscriber');
9305 var async_1 = require('../scheduler/async');
9306 /**
9307  * Emits a value from the source Observable only after a particular time span
9308  * has passed without another source emission.
9309  *
9310  * <span class="informal">It's like {@link delay}, but passes only the most
9311  * recent value from each burst of emissions.</span>
9312  *
9313  * <img src="./img/debounceTime.png" width="100%">
9314  *
9315  * `debounceTime` delays values emitted by the source Observable, but drops
9316  * previous pending delayed emissions if a new value arrives on the source
9317  * Observable. This operator keeps track of the most recent value from the
9318  * source Observable, and emits that only when `dueTime` enough time has passed
9319  * without any other value appearing on the source Observable. If a new value
9320  * appears before `dueTime` silence occurs, the previous value will be dropped
9321  * and will not be emitted on the output Observable.
9322  *
9323  * This is a rate-limiting operator, because it is impossible for more than one
9324  * value to be emitted in any time window of duration `dueTime`, but it is also
9325  * a delay-like operator since output emissions do not occur at the same time as
9326  * they did on the source Observable. Optionally takes a {@link IScheduler} for
9327  * managing timers.
9328  *
9329  * @example <caption>Emit the most recent click after a burst of clicks</caption>
9330  * var clicks = Rx.Observable.fromEvent(document, 'click');
9331  * var result = clicks.debounceTime(1000);
9332  * result.subscribe(x => console.log(x));
9333  *
9334  * @see {@link auditTime}
9335  * @see {@link debounce}
9336  * @see {@link delay}
9337  * @see {@link sampleTime}
9338  * @see {@link throttleTime}
9339  *
9340  * @param {number} dueTime The timeout duration in milliseconds (or the time
9341  * unit determined internally by the optional `scheduler`) for the window of
9342  * time required to wait for emission silence before emitting the most recent
9343  * source value.
9344  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9345  * managing the timers that handle the timeout for each value.
9346  * @return {Observable} An Observable that delays the emissions of the source
9347  * Observable by the specified `dueTime`, and may drop some values if they occur
9348  * too frequently.
9349  * @method debounceTime
9350  * @owner Observable
9351  */
9352 function debounceTime(dueTime, scheduler) {
9353     if (scheduler === void 0) { scheduler = async_1.async; }
9354     return this.lift(new DebounceTimeOperator(dueTime, scheduler));
9355 }
9356 exports.debounceTime = debounceTime;
9357 var DebounceTimeOperator = (function () {
9358     function DebounceTimeOperator(dueTime, scheduler) {
9359         this.dueTime = dueTime;
9360         this.scheduler = scheduler;
9361     }
9362     DebounceTimeOperator.prototype.call = function (subscriber, source) {
9363         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9364     };
9365     return DebounceTimeOperator;
9366 }());
9367 /**
9368  * We need this JSDoc comment for affecting ESDoc.
9369  * @ignore
9370  * @extends {Ignored}
9371  */
9372 var DebounceTimeSubscriber = (function (_super) {
9373     __extends(DebounceTimeSubscriber, _super);
9374     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9375         _super.call(this, destination);
9376         this.dueTime = dueTime;
9377         this.scheduler = scheduler;
9378         this.debouncedSubscription = null;
9379         this.lastValue = null;
9380         this.hasValue = false;
9381     }
9382     DebounceTimeSubscriber.prototype._next = function (value) {
9383         this.clearDebounce();
9384         this.lastValue = value;
9385         this.hasValue = true;
9386         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9387     };
9388     DebounceTimeSubscriber.prototype._complete = function () {
9389         this.debouncedNext();
9390         this.destination.complete();
9391     };
9392     DebounceTimeSubscriber.prototype.debouncedNext = function () {
9393         this.clearDebounce();
9394         if (this.hasValue) {
9395             this.destination.next(this.lastValue);
9396             this.lastValue = null;
9397             this.hasValue = false;
9398         }
9399     };
9400     DebounceTimeSubscriber.prototype.clearDebounce = function () {
9401         var debouncedSubscription = this.debouncedSubscription;
9402         if (debouncedSubscription !== null) {
9403             this.remove(debouncedSubscription);
9404             debouncedSubscription.unsubscribe();
9405             this.debouncedSubscription = null;
9406         }
9407     };
9408     return DebounceTimeSubscriber;
9409 }(Subscriber_1.Subscriber));
9410 function dispatchNext(subscriber) {
9411     subscriber.debouncedNext();
9412 }
9413
9414 },{"../Subscriber":36,"../scheduler/async":156}],117:[function(require,module,exports){
9415 "use strict";
9416 var __extends = (this && this.__extends) || function (d, b) {
9417     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9418     function __() { this.constructor = d; }
9419     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9420 };
9421 var async_1 = require('../scheduler/async');
9422 var isDate_1 = require('../util/isDate');
9423 var Subscriber_1 = require('../Subscriber');
9424 var Notification_1 = require('../Notification');
9425 /**
9426  * Delays the emission of items from the source Observable by a given timeout or
9427  * until a given Date.
9428  *
9429  * <span class="informal">Time shifts each item by some specified amount of
9430  * milliseconds.</span>
9431  *
9432  * <img src="./img/delay.png" width="100%">
9433  *
9434  * If the delay argument is a Number, this operator time shifts the source
9435  * Observable by that amount of time expressed in milliseconds. The relative
9436  * time intervals between the values are preserved.
9437  *
9438  * If the delay argument is a Date, this operator time shifts the start of the
9439  * Observable execution until the given date occurs.
9440  *
9441  * @example <caption>Delay each click by one second</caption>
9442  * var clicks = Rx.Observable.fromEvent(document, 'click');
9443  * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9444  * delayedClicks.subscribe(x => console.log(x));
9445  *
9446  * @example <caption>Delay all clicks until a future date happens</caption>
9447  * var clicks = Rx.Observable.fromEvent(document, 'click');
9448  * var date = new Date('March 15, 2050 12:00:00'); // in the future
9449  * var delayedClicks = clicks.delay(date); // click emitted only after that date
9450  * delayedClicks.subscribe(x => console.log(x));
9451  *
9452  * @see {@link debounceTime}
9453  * @see {@link delayWhen}
9454  *
9455  * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9456  * a `Date` until which the emission of the source items is delayed.
9457  * @param {Scheduler} [scheduler=async] The IScheduler to use for
9458  * managing the timers that handle the time-shift for each item.
9459  * @return {Observable} An Observable that delays the emissions of the source
9460  * Observable by the specified timeout or Date.
9461  * @method delay
9462  * @owner Observable
9463  */
9464 function delay(delay, scheduler) {
9465     if (scheduler === void 0) { scheduler = async_1.async; }
9466     var absoluteDelay = isDate_1.isDate(delay);
9467     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9468     return this.lift(new DelayOperator(delayFor, scheduler));
9469 }
9470 exports.delay = delay;
9471 var DelayOperator = (function () {
9472     function DelayOperator(delay, scheduler) {
9473         this.delay = delay;
9474         this.scheduler = scheduler;
9475     }
9476     DelayOperator.prototype.call = function (subscriber, source) {
9477         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9478     };
9479     return DelayOperator;
9480 }());
9481 /**
9482  * We need this JSDoc comment for affecting ESDoc.
9483  * @ignore
9484  * @extends {Ignored}
9485  */
9486 var DelaySubscriber = (function (_super) {
9487     __extends(DelaySubscriber, _super);
9488     function DelaySubscriber(destination, delay, scheduler) {
9489         _super.call(this, destination);
9490         this.delay = delay;
9491         this.scheduler = scheduler;
9492         this.queue = [];
9493         this.active = false;
9494         this.errored = false;
9495     }
9496     DelaySubscriber.dispatch = function (state) {
9497         var source = state.source;
9498         var queue = source.queue;
9499         var scheduler = state.scheduler;
9500         var destination = state.destination;
9501         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9502             queue.shift().notification.observe(destination);
9503         }
9504         if (queue.length > 0) {
9505             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9506             this.schedule(state, delay_1);
9507         }
9508         else {
9509             source.active = false;
9510         }
9511     };
9512     DelaySubscriber.prototype._schedule = function (scheduler) {
9513         this.active = true;
9514         this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9515             source: this, destination: this.destination, scheduler: scheduler
9516         }));
9517     };
9518     DelaySubscriber.prototype.scheduleNotification = function (notification) {
9519         if (this.errored === true) {
9520             return;
9521         }
9522         var scheduler = this.scheduler;
9523         var message = new DelayMessage(scheduler.now() + this.delay, notification);
9524         this.queue.push(message);
9525         if (this.active === false) {
9526             this._schedule(scheduler);
9527         }
9528     };
9529     DelaySubscriber.prototype._next = function (value) {
9530         this.scheduleNotification(Notification_1.Notification.createNext(value));
9531     };
9532     DelaySubscriber.prototype._error = function (err) {
9533         this.errored = true;
9534         this.queue = [];
9535         this.destination.error(err);
9536     };
9537     DelaySubscriber.prototype._complete = function () {
9538         this.scheduleNotification(Notification_1.Notification.createComplete());
9539     };
9540     return DelaySubscriber;
9541 }(Subscriber_1.Subscriber));
9542 var DelayMessage = (function () {
9543     function DelayMessage(time, notification) {
9544         this.time = time;
9545         this.notification = notification;
9546     }
9547     return DelayMessage;
9548 }());
9549
9550 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":156,"../util/isDate":170}],118:[function(require,module,exports){
9551 "use strict";
9552 var __extends = (this && this.__extends) || function (d, b) {
9553     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9554     function __() { this.constructor = d; }
9555     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9556 };
9557 var OuterSubscriber_1 = require('../OuterSubscriber');
9558 var subscribeToResult_1 = require('../util/subscribeToResult');
9559 var Set_1 = require('../util/Set');
9560 /**
9561  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9562  *
9563  * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9564  * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9565  * source observable directly with an equality check against previous values.
9566  *
9567  * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9568  *
9569  * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9570  * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9571  * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9572  * that the internal `Set` can be "flushed", basically clearing it of values.
9573  *
9574  * @example <caption>A simple example with numbers</caption>
9575  * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9576  *   .distinct()
9577  *   .subscribe(x => console.log(x)); // 1, 2, 3, 4
9578  *
9579  * @example <caption>An example using a keySelector function</caption>
9580  * interface Person {
9581  *    age: number,
9582  *    name: string
9583  * }
9584  *
9585  * Observable.of<Person>(
9586  *     { age: 4, name: 'Foo'},
9587  *     { age: 7, name: 'Bar'},
9588  *     { age: 5, name: 'Foo'})
9589  *     .distinct((p: Person) => p.name)
9590  *     .subscribe(x => console.log(x));
9591  *
9592  * // displays:
9593  * // { age: 4, name: 'Foo' }
9594  * // { age: 7, name: 'Bar' }
9595  *
9596  * @see {@link distinctUntilChanged}
9597  * @see {@link distinctUntilKeyChanged}
9598  *
9599  * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9600  * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9601  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9602  * @method distinct
9603  * @owner Observable
9604  */
9605 function distinct(keySelector, flushes) {
9606     return this.lift(new DistinctOperator(keySelector, flushes));
9607 }
9608 exports.distinct = distinct;
9609 var DistinctOperator = (function () {
9610     function DistinctOperator(keySelector, flushes) {
9611         this.keySelector = keySelector;
9612         this.flushes = flushes;
9613     }
9614     DistinctOperator.prototype.call = function (subscriber, source) {
9615         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9616     };
9617     return DistinctOperator;
9618 }());
9619 /**
9620  * We need this JSDoc comment for affecting ESDoc.
9621  * @ignore
9622  * @extends {Ignored}
9623  */
9624 var DistinctSubscriber = (function (_super) {
9625     __extends(DistinctSubscriber, _super);
9626     function DistinctSubscriber(destination, keySelector, flushes) {
9627         _super.call(this, destination);
9628         this.keySelector = keySelector;
9629         this.values = new Set_1.Set();
9630         if (flushes) {
9631             this.add(subscribeToResult_1.subscribeToResult(this, flushes));
9632         }
9633     }
9634     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9635         this.values.clear();
9636     };
9637     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9638         this._error(error);
9639     };
9640     DistinctSubscriber.prototype._next = function (value) {
9641         if (this.keySelector) {
9642             this._useKeySelector(value);
9643         }
9644         else {
9645             this._finalizeNext(value, value);
9646         }
9647     };
9648     DistinctSubscriber.prototype._useKeySelector = function (value) {
9649         var key;
9650         var destination = this.destination;
9651         try {
9652             key = this.keySelector(value);
9653         }
9654         catch (err) {
9655             destination.error(err);
9656             return;
9657         }
9658         this._finalizeNext(key, value);
9659     };
9660     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9661         var values = this.values;
9662         if (!values.has(key)) {
9663             values.add(key);
9664             this.destination.next(value);
9665         }
9666     };
9667     return DistinctSubscriber;
9668 }(OuterSubscriber_1.OuterSubscriber));
9669 exports.DistinctSubscriber = DistinctSubscriber;
9670
9671 },{"../OuterSubscriber":31,"../util/Set":165,"../util/subscribeToResult":177}],119:[function(require,module,exports){
9672 "use strict";
9673 var __extends = (this && this.__extends) || function (d, b) {
9674     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9675     function __() { this.constructor = d; }
9676     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9677 };
9678 var Subscriber_1 = require('../Subscriber');
9679 var tryCatch_1 = require('../util/tryCatch');
9680 var errorObject_1 = require('../util/errorObject');
9681 /* tslint:enable:max-line-length */
9682 /**
9683  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9684  *
9685  * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
9686  *
9687  * If a comparator function is not provided, an equality check is used by default.
9688  *
9689  * @example <caption>A simple example with numbers</caption>
9690  * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9691  *   .distinctUntilChanged()
9692  *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9693  *
9694  * @example <caption>An example using a compare function</caption>
9695  * interface Person {
9696  *    age: number,
9697  *    name: string
9698  * }
9699  *
9700  * Observable.of<Person>(
9701  *     { age: 4, name: 'Foo'},
9702  *     { age: 7, name: 'Bar'},
9703  *     { age: 5, name: 'Foo'})
9704  *     { age: 6, name: 'Foo'})
9705  *     .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9706  *     .subscribe(x => console.log(x));
9707  *
9708  * // displays:
9709  * // { age: 4, name: 'Foo' }
9710  * // { age: 7, name: 'Bar' }
9711  * // { age: 5, name: 'Foo' }
9712  *
9713  * @see {@link distinct}
9714  * @see {@link distinctUntilKeyChanged}
9715  *
9716  * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9717  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9718  * @method distinctUntilChanged
9719  * @owner Observable
9720  */
9721 function distinctUntilChanged(compare, keySelector) {
9722     return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
9723 }
9724 exports.distinctUntilChanged = distinctUntilChanged;
9725 var DistinctUntilChangedOperator = (function () {
9726     function DistinctUntilChangedOperator(compare, keySelector) {
9727         this.compare = compare;
9728         this.keySelector = keySelector;
9729     }
9730     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9731         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9732     };
9733     return DistinctUntilChangedOperator;
9734 }());
9735 /**
9736  * We need this JSDoc comment for affecting ESDoc.
9737  * @ignore
9738  * @extends {Ignored}
9739  */
9740 var DistinctUntilChangedSubscriber = (function (_super) {
9741     __extends(DistinctUntilChangedSubscriber, _super);
9742     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9743         _super.call(this, destination);
9744         this.keySelector = keySelector;
9745         this.hasKey = false;
9746         if (typeof compare === 'function') {
9747             this.compare = compare;
9748         }
9749     }
9750     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9751         return x === y;
9752     };
9753     DistinctUntilChangedSubscriber.prototype._next = function (value) {
9754         var keySelector = this.keySelector;
9755         var key = value;
9756         if (keySelector) {
9757             key = tryCatch_1.tryCatch(this.keySelector)(value);
9758             if (key === errorObject_1.errorObject) {
9759                 return this.destination.error(errorObject_1.errorObject.e);
9760             }
9761         }
9762         var result = false;
9763         if (this.hasKey) {
9764             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9765             if (result === errorObject_1.errorObject) {
9766                 return this.destination.error(errorObject_1.errorObject.e);
9767             }
9768         }
9769         else {
9770             this.hasKey = true;
9771         }
9772         if (Boolean(result) === false) {
9773             this.key = key;
9774             this.destination.next(value);
9775         }
9776     };
9777     return DistinctUntilChangedSubscriber;
9778 }(Subscriber_1.Subscriber));
9779
9780 },{"../Subscriber":36,"../util/errorObject":167,"../util/tryCatch":179}],120:[function(require,module,exports){
9781 "use strict";
9782 var __extends = (this && this.__extends) || function (d, b) {
9783     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9784     function __() { this.constructor = d; }
9785     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9786 };
9787 var Subscriber_1 = require('../Subscriber');
9788 /* tslint:enable:max-line-length */
9789 /**
9790  * Perform a side effect for every emission on the source Observable, but return
9791  * an Observable that is identical to the source.
9792  *
9793  * <span class="informal">Intercepts each emission on the source and runs a
9794  * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9795  *
9796  * <img src="./img/do.png" width="100%">
9797  *
9798  * Returns a mirrored Observable of the source Observable, but modified so that
9799  * the provided Observer is called to perform a side effect for every value,
9800  * error, and completion emitted by the source. Any errors that are thrown in
9801  * the aforementioned Observer or handlers are safely sent down the error path
9802  * of the output Observable.
9803  *
9804  * This operator is useful for debugging your Observables for the correct values
9805  * or performing other side effects.
9806  *
9807  * Note: this is different to a `subscribe` on the Observable. If the Observable
9808  * returned by `do` is not subscribed, the side effects specified by the
9809  * Observer will never happen. `do` therefore simply spies on existing
9810  * execution, it does not trigger an execution to happen like `subscribe` does.
9811  *
9812  * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9813  * var clicks = Rx.Observable.fromEvent(document, 'click');
9814  * var positions = clicks
9815  *   .do(ev => console.log(ev))
9816  *   .map(ev => ev.clientX);
9817  * positions.subscribe(x => console.log(x));
9818  *
9819  * @see {@link map}
9820  * @see {@link subscribe}
9821  *
9822  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9823  * callback for `next`.
9824  * @param {function} [error] Callback for errors in the source.
9825  * @param {function} [complete] Callback for the completion of the source.
9826  * @return {Observable} An Observable identical to the source, but runs the
9827  * specified Observer or callback(s) for each item.
9828  * @method do
9829  * @name do
9830  * @owner Observable
9831  */
9832 function _do(nextOrObserver, error, complete) {
9833     return this.lift(new DoOperator(nextOrObserver, error, complete));
9834 }
9835 exports._do = _do;
9836 var DoOperator = (function () {
9837     function DoOperator(nextOrObserver, error, complete) {
9838         this.nextOrObserver = nextOrObserver;
9839         this.error = error;
9840         this.complete = complete;
9841     }
9842     DoOperator.prototype.call = function (subscriber, source) {
9843         return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9844     };
9845     return DoOperator;
9846 }());
9847 /**
9848  * We need this JSDoc comment for affecting ESDoc.
9849  * @ignore
9850  * @extends {Ignored}
9851  */
9852 var DoSubscriber = (function (_super) {
9853     __extends(DoSubscriber, _super);
9854     function DoSubscriber(destination, nextOrObserver, error, complete) {
9855         _super.call(this, destination);
9856         var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9857         safeSubscriber.syncErrorThrowable = true;
9858         this.add(safeSubscriber);
9859         this.safeSubscriber = safeSubscriber;
9860     }
9861     DoSubscriber.prototype._next = function (value) {
9862         var safeSubscriber = this.safeSubscriber;
9863         safeSubscriber.next(value);
9864         if (safeSubscriber.syncErrorThrown) {
9865             this.destination.error(safeSubscriber.syncErrorValue);
9866         }
9867         else {
9868             this.destination.next(value);
9869         }
9870     };
9871     DoSubscriber.prototype._error = function (err) {
9872         var safeSubscriber = this.safeSubscriber;
9873         safeSubscriber.error(err);
9874         if (safeSubscriber.syncErrorThrown) {
9875             this.destination.error(safeSubscriber.syncErrorValue);
9876         }
9877         else {
9878             this.destination.error(err);
9879         }
9880     };
9881     DoSubscriber.prototype._complete = function () {
9882         var safeSubscriber = this.safeSubscriber;
9883         safeSubscriber.complete();
9884         if (safeSubscriber.syncErrorThrown) {
9885             this.destination.error(safeSubscriber.syncErrorValue);
9886         }
9887         else {
9888             this.destination.complete();
9889         }
9890     };
9891     return DoSubscriber;
9892 }(Subscriber_1.Subscriber));
9893
9894 },{"../Subscriber":36}],121:[function(require,module,exports){
9895 "use strict";
9896 var __extends = (this && this.__extends) || function (d, b) {
9897     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9898     function __() { this.constructor = d; }
9899     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9900 };
9901 var tryCatch_1 = require('../util/tryCatch');
9902 var errorObject_1 = require('../util/errorObject');
9903 var OuterSubscriber_1 = require('../OuterSubscriber');
9904 var subscribeToResult_1 = require('../util/subscribeToResult');
9905 /* tslint:enable:max-line-length */
9906 /**
9907  * Recursively projects each source value to an Observable which is merged in
9908  * the output Observable.
9909  *
9910  * <span class="informal">It's similar to {@link mergeMap}, but applies the
9911  * projection function to every source value as well as every output value.
9912  * It's recursive.</span>
9913  *
9914  * <img src="./img/expand.png" width="100%">
9915  *
9916  * Returns an Observable that emits items based on applying a function that you
9917  * supply to each item emitted by the source Observable, where that function
9918  * returns an Observable, and then merging those resulting Observables and
9919  * emitting the results of this merger. *Expand* will re-emit on the output
9920  * Observable every source value. Then, each output value is given to the
9921  * `project` function which returns an inner Observable to be merged on the
9922  * output Observable. Those output values resulting from the projection are also
9923  * given to the `project` function to produce new output values. This is how
9924  * *expand* behaves recursively.
9925  *
9926  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9927  * var clicks = Rx.Observable.fromEvent(document, 'click');
9928  * var powersOfTwo = clicks
9929  *   .mapTo(1)
9930  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
9931  *   .take(10);
9932  * powersOfTwo.subscribe(x => console.log(x));
9933  *
9934  * @see {@link mergeMap}
9935  * @see {@link mergeScan}
9936  *
9937  * @param {function(value: T, index: number) => Observable} project A function
9938  * that, when applied to an item emitted by the source or the output Observable,
9939  * returns an Observable.
9940  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9941  * Observables being subscribed to concurrently.
9942  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9943  * each projected inner Observable.
9944  * @return {Observable} An Observable that emits the source values and also
9945  * result of applying the projection function to each value emitted on the
9946  * output Observable and and merging the results of the Observables obtained
9947  * from this transformation.
9948  * @method expand
9949  * @owner Observable
9950  */
9951 function expand(project, concurrent, scheduler) {
9952     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9953     if (scheduler === void 0) { scheduler = undefined; }
9954     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9955     return this.lift(new ExpandOperator(project, concurrent, scheduler));
9956 }
9957 exports.expand = expand;
9958 var ExpandOperator = (function () {
9959     function ExpandOperator(project, concurrent, scheduler) {
9960         this.project = project;
9961         this.concurrent = concurrent;
9962         this.scheduler = scheduler;
9963     }
9964     ExpandOperator.prototype.call = function (subscriber, source) {
9965         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9966     };
9967     return ExpandOperator;
9968 }());
9969 exports.ExpandOperator = ExpandOperator;
9970 /**
9971  * We need this JSDoc comment for affecting ESDoc.
9972  * @ignore
9973  * @extends {Ignored}
9974  */
9975 var ExpandSubscriber = (function (_super) {
9976     __extends(ExpandSubscriber, _super);
9977     function ExpandSubscriber(destination, project, concurrent, scheduler) {
9978         _super.call(this, destination);
9979         this.project = project;
9980         this.concurrent = concurrent;
9981         this.scheduler = scheduler;
9982         this.index = 0;
9983         this.active = 0;
9984         this.hasCompleted = false;
9985         if (concurrent < Number.POSITIVE_INFINITY) {
9986             this.buffer = [];
9987         }
9988     }
9989     ExpandSubscriber.dispatch = function (arg) {
9990         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9991         subscriber.subscribeToProjection(result, value, index);
9992     };
9993     ExpandSubscriber.prototype._next = function (value) {
9994         var destination = this.destination;
9995         if (destination.closed) {
9996             this._complete();
9997             return;
9998         }
9999         var index = this.index++;
10000         if (this.active < this.concurrent) {
10001             destination.next(value);
10002             var result = tryCatch_1.tryCatch(this.project)(value, index);
10003             if (result === errorObject_1.errorObject) {
10004                 destination.error(errorObject_1.errorObject.e);
10005             }
10006             else if (!this.scheduler) {
10007                 this.subscribeToProjection(result, value, index);
10008             }
10009             else {
10010                 var state = { subscriber: this, result: result, value: value, index: index };
10011                 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
10012             }
10013         }
10014         else {
10015             this.buffer.push(value);
10016         }
10017     };
10018     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
10019         this.active++;
10020         this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
10021     };
10022     ExpandSubscriber.prototype._complete = function () {
10023         this.hasCompleted = true;
10024         if (this.hasCompleted && this.active === 0) {
10025             this.destination.complete();
10026         }
10027     };
10028     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10029         this._next(innerValue);
10030     };
10031     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
10032         var buffer = this.buffer;
10033         this.remove(innerSub);
10034         this.active--;
10035         if (buffer && buffer.length > 0) {
10036             this._next(buffer.shift());
10037         }
10038         if (this.hasCompleted && this.active === 0) {
10039             this.destination.complete();
10040         }
10041     };
10042     return ExpandSubscriber;
10043 }(OuterSubscriber_1.OuterSubscriber));
10044 exports.ExpandSubscriber = ExpandSubscriber;
10045
10046 },{"../OuterSubscriber":31,"../util/errorObject":167,"../util/subscribeToResult":177,"../util/tryCatch":179}],122:[function(require,module,exports){
10047 "use strict";
10048 var __extends = (this && this.__extends) || function (d, b) {
10049     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10050     function __() { this.constructor = d; }
10051     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10052 };
10053 var Subscriber_1 = require('../Subscriber');
10054 /* tslint:enable:max-line-length */
10055 /**
10056  * Filter items emitted by the source Observable by only emitting those that
10057  * satisfy a specified predicate.
10058  *
10059  * <span class="informal">Like
10060  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
10061  * it only emits a value from the source if it passes a criterion function.</span>
10062  *
10063  * <img src="./img/filter.png" width="100%">
10064  *
10065  * Similar to the well-known `Array.prototype.filter` method, this operator
10066  * takes values from the source Observable, passes them through a `predicate`
10067  * function and only emits those values that yielded `true`.
10068  *
10069  * @example <caption>Emit only click events whose target was a DIV element</caption>
10070  * var clicks = Rx.Observable.fromEvent(document, 'click');
10071  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
10072  * clicksOnDivs.subscribe(x => console.log(x));
10073  *
10074  * @see {@link distinct}
10075  * @see {@link distinctUntilChanged}
10076  * @see {@link distinctUntilKeyChanged}
10077  * @see {@link ignoreElements}
10078  * @see {@link partition}
10079  * @see {@link skip}
10080  *
10081  * @param {function(value: T, index: number): boolean} predicate A function that
10082  * evaluates each value emitted by the source Observable. If it returns `true`,
10083  * the value is emitted, if `false` the value is not passed to the output
10084  * Observable. The `index` parameter is the number `i` for the i-th source
10085  * emission that has happened since the subscription, starting from the number
10086  * `0`.
10087  * @param {any} [thisArg] An optional argument to determine the value of `this`
10088  * in the `predicate` function.
10089  * @return {Observable} An Observable of values from the source that were
10090  * allowed by the `predicate` function.
10091  * @method filter
10092  * @owner Observable
10093  */
10094 function filter(predicate, thisArg) {
10095     return this.lift(new FilterOperator(predicate, thisArg));
10096 }
10097 exports.filter = filter;
10098 var FilterOperator = (function () {
10099     function FilterOperator(predicate, thisArg) {
10100         this.predicate = predicate;
10101         this.thisArg = thisArg;
10102     }
10103     FilterOperator.prototype.call = function (subscriber, source) {
10104         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
10105     };
10106     return FilterOperator;
10107 }());
10108 /**
10109  * We need this JSDoc comment for affecting ESDoc.
10110  * @ignore
10111  * @extends {Ignored}
10112  */
10113 var FilterSubscriber = (function (_super) {
10114     __extends(FilterSubscriber, _super);
10115     function FilterSubscriber(destination, predicate, thisArg) {
10116         _super.call(this, destination);
10117         this.predicate = predicate;
10118         this.thisArg = thisArg;
10119         this.count = 0;
10120         this.predicate = predicate;
10121     }
10122     // the try catch block below is left specifically for
10123     // optimization and perf reasons. a tryCatcher is not necessary here.
10124     FilterSubscriber.prototype._next = function (value) {
10125         var result;
10126         try {
10127             result = this.predicate.call(this.thisArg, value, this.count++);
10128         }
10129         catch (err) {
10130             this.destination.error(err);
10131             return;
10132         }
10133         if (result) {
10134             this.destination.next(value);
10135         }
10136     };
10137     return FilterSubscriber;
10138 }(Subscriber_1.Subscriber));
10139
10140 },{"../Subscriber":36}],123:[function(require,module,exports){
10141 "use strict";
10142 var __extends = (this && this.__extends) || function (d, b) {
10143     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10144     function __() { this.constructor = d; }
10145     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10146 };
10147 var Subscriber_1 = require('../Subscriber');
10148 var Subscription_1 = require('../Subscription');
10149 /**
10150  * Returns an Observable that mirrors the source Observable, but will call a specified function when
10151  * the source terminates on complete or error.
10152  * @param {function} callback Function to be called when source terminates.
10153  * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
10154  * @method finally
10155  * @owner Observable
10156  */
10157 function _finally(callback) {
10158     return this.lift(new FinallyOperator(callback));
10159 }
10160 exports._finally = _finally;
10161 var FinallyOperator = (function () {
10162     function FinallyOperator(callback) {
10163         this.callback = callback;
10164     }
10165     FinallyOperator.prototype.call = function (subscriber, source) {
10166         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
10167     };
10168     return FinallyOperator;
10169 }());
10170 /**
10171  * We need this JSDoc comment for affecting ESDoc.
10172  * @ignore
10173  * @extends {Ignored}
10174  */
10175 var FinallySubscriber = (function (_super) {
10176     __extends(FinallySubscriber, _super);
10177     function FinallySubscriber(destination, callback) {
10178         _super.call(this, destination);
10179         this.add(new Subscription_1.Subscription(callback));
10180     }
10181     return FinallySubscriber;
10182 }(Subscriber_1.Subscriber));
10183
10184 },{"../Subscriber":36,"../Subscription":37}],124:[function(require,module,exports){
10185 "use strict";
10186 var __extends = (this && this.__extends) || function (d, b) {
10187     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10188     function __() { this.constructor = d; }
10189     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10190 };
10191 var Subscriber_1 = require('../Subscriber');
10192 var EmptyError_1 = require('../util/EmptyError');
10193 /**
10194  * Emits only the first value (or the first value that meets some condition)
10195  * emitted by the source Observable.
10196  *
10197  * <span class="informal">Emits only the first value. Or emits only the first
10198  * value that passes some test.</span>
10199  *
10200  * <img src="./img/first.png" width="100%">
10201  *
10202  * If called with no arguments, `first` emits the first value of the source
10203  * Observable, then completes. If called with a `predicate` function, `first`
10204  * emits the first value of the source that matches the specified condition. It
10205  * may also take a `resultSelector` function to produce the output value from
10206  * the input value, and a `defaultValue` to emit in case the source completes
10207  * before it is able to emit a valid value. Throws an error if `defaultValue`
10208  * was not provided and a matching element is not found.
10209  *
10210  * @example <caption>Emit only the first click that happens on the DOM</caption>
10211  * var clicks = Rx.Observable.fromEvent(document, 'click');
10212  * var result = clicks.first();
10213  * result.subscribe(x => console.log(x));
10214  *
10215  * @example <caption>Emits the first click that happens on a DIV</caption>
10216  * var clicks = Rx.Observable.fromEvent(document, 'click');
10217  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
10218  * result.subscribe(x => console.log(x));
10219  *
10220  * @see {@link filter}
10221  * @see {@link find}
10222  * @see {@link take}
10223  *
10224  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10225  * callback if the Observable completes before any `next` notification was sent.
10226  *
10227  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
10228  * An optional function called with each item to test for condition matching.
10229  * @param {function(value: T, index: number): R} [resultSelector] A function to
10230  * produce the value on the output Observable based on the values
10231  * and the indices of the source Observable. The arguments passed to this
10232  * function are:
10233  * - `value`: the value that was emitted on the source.
10234  * - `index`: the "index" of the value from the source.
10235  * @param {R} [defaultValue] The default value emitted in case no valid value
10236  * was found on the source.
10237  * @return {Observable<T|R>} An Observable of the first item that matches the
10238  * condition.
10239  * @method first
10240  * @owner Observable
10241  */
10242 function first(predicate, resultSelector, defaultValue) {
10243     return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
10244 }
10245 exports.first = first;
10246 var FirstOperator = (function () {
10247     function FirstOperator(predicate, resultSelector, defaultValue, source) {
10248         this.predicate = predicate;
10249         this.resultSelector = resultSelector;
10250         this.defaultValue = defaultValue;
10251         this.source = source;
10252     }
10253     FirstOperator.prototype.call = function (observer, source) {
10254         return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10255     };
10256     return FirstOperator;
10257 }());
10258 /**
10259  * We need this JSDoc comment for affecting ESDoc.
10260  * @ignore
10261  * @extends {Ignored}
10262  */
10263 var FirstSubscriber = (function (_super) {
10264     __extends(FirstSubscriber, _super);
10265     function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10266         _super.call(this, destination);
10267         this.predicate = predicate;
10268         this.resultSelector = resultSelector;
10269         this.defaultValue = defaultValue;
10270         this.source = source;
10271         this.index = 0;
10272         this.hasCompleted = false;
10273         this._emitted = false;
10274     }
10275     FirstSubscriber.prototype._next = function (value) {
10276         var index = this.index++;
10277         if (this.predicate) {
10278             this._tryPredicate(value, index);
10279         }
10280         else {
10281             this._emit(value, index);
10282         }
10283     };
10284     FirstSubscriber.prototype._tryPredicate = function (value, index) {
10285         var result;
10286         try {
10287             result = this.predicate(value, index, this.source);
10288         }
10289         catch (err) {
10290             this.destination.error(err);
10291             return;
10292         }
10293         if (result) {
10294             this._emit(value, index);
10295         }
10296     };
10297     FirstSubscriber.prototype._emit = function (value, index) {
10298         if (this.resultSelector) {
10299             this._tryResultSelector(value, index);
10300             return;
10301         }
10302         this._emitFinal(value);
10303     };
10304     FirstSubscriber.prototype._tryResultSelector = function (value, index) {
10305         var result;
10306         try {
10307             result = this.resultSelector(value, index);
10308         }
10309         catch (err) {
10310             this.destination.error(err);
10311             return;
10312         }
10313         this._emitFinal(result);
10314     };
10315     FirstSubscriber.prototype._emitFinal = function (value) {
10316         var destination = this.destination;
10317         if (!this._emitted) {
10318             this._emitted = true;
10319             destination.next(value);
10320             destination.complete();
10321             this.hasCompleted = true;
10322         }
10323     };
10324     FirstSubscriber.prototype._complete = function () {
10325         var destination = this.destination;
10326         if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
10327             destination.next(this.defaultValue);
10328             destination.complete();
10329         }
10330         else if (!this.hasCompleted) {
10331             destination.error(new EmptyError_1.EmptyError);
10332         }
10333     };
10334     return FirstSubscriber;
10335 }(Subscriber_1.Subscriber));
10336
10337 },{"../Subscriber":36,"../util/EmptyError":163}],125:[function(require,module,exports){
10338 "use strict";
10339 var __extends = (this && this.__extends) || function (d, b) {
10340     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10341     function __() { this.constructor = d; }
10342     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10343 };
10344 var Subscriber_1 = require('../Subscriber');
10345 var EmptyError_1 = require('../util/EmptyError');
10346 /* tslint:enable:max-line-length */
10347 /**
10348  * Returns an Observable that emits only the last item emitted by the source Observable.
10349  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
10350  * the last item from the source Observable, the resulting Observable will emit the last item
10351  * from the source Observable that satisfies the predicate.
10352  *
10353  * <img src="./img/last.png" width="100%">
10354  *
10355  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10356  * callback if the Observable completes before any `next` notification was sent.
10357  * @param {function} predicate - The condition any source emitted item has to satisfy.
10358  * @return {Observable} An Observable that emits only the last item satisfying the given condition
10359  * from the source, or an NoSuchElementException if no such items are emitted.
10360  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
10361  * @method last
10362  * @owner Observable
10363  */
10364 function last(predicate, resultSelector, defaultValue) {
10365     return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
10366 }
10367 exports.last = last;
10368 var LastOperator = (function () {
10369     function LastOperator(predicate, resultSelector, defaultValue, source) {
10370         this.predicate = predicate;
10371         this.resultSelector = resultSelector;
10372         this.defaultValue = defaultValue;
10373         this.source = source;
10374     }
10375     LastOperator.prototype.call = function (observer, source) {
10376         return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10377     };
10378     return LastOperator;
10379 }());
10380 /**
10381  * We need this JSDoc comment for affecting ESDoc.
10382  * @ignore
10383  * @extends {Ignored}
10384  */
10385 var LastSubscriber = (function (_super) {
10386     __extends(LastSubscriber, _super);
10387     function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10388         _super.call(this, destination);
10389         this.predicate = predicate;
10390         this.resultSelector = resultSelector;
10391         this.defaultValue = defaultValue;
10392         this.source = source;
10393         this.hasValue = false;
10394         this.index = 0;
10395         if (typeof defaultValue !== 'undefined') {
10396             this.lastValue = defaultValue;
10397             this.hasValue = true;
10398         }
10399     }
10400     LastSubscriber.prototype._next = function (value) {
10401         var index = this.index++;
10402         if (this.predicate) {
10403             this._tryPredicate(value, index);
10404         }
10405         else {
10406             if (this.resultSelector) {
10407                 this._tryResultSelector(value, index);
10408                 return;
10409             }
10410             this.lastValue = value;
10411             this.hasValue = true;
10412         }
10413     };
10414     LastSubscriber.prototype._tryPredicate = function (value, index) {
10415         var result;
10416         try {
10417             result = this.predicate(value, index, this.source);
10418         }
10419         catch (err) {
10420             this.destination.error(err);
10421             return;
10422         }
10423         if (result) {
10424             if (this.resultSelector) {
10425                 this._tryResultSelector(value, index);
10426                 return;
10427             }
10428             this.lastValue = value;
10429             this.hasValue = true;
10430         }
10431     };
10432     LastSubscriber.prototype._tryResultSelector = function (value, index) {
10433         var result;
10434         try {
10435             result = this.resultSelector(value, index);
10436         }
10437         catch (err) {
10438             this.destination.error(err);
10439             return;
10440         }
10441         this.lastValue = result;
10442         this.hasValue = true;
10443     };
10444     LastSubscriber.prototype._complete = function () {
10445         var destination = this.destination;
10446         if (this.hasValue) {
10447             destination.next(this.lastValue);
10448             destination.complete();
10449         }
10450         else {
10451             destination.error(new EmptyError_1.EmptyError);
10452         }
10453     };
10454     return LastSubscriber;
10455 }(Subscriber_1.Subscriber));
10456
10457 },{"../Subscriber":36,"../util/EmptyError":163}],126:[function(require,module,exports){
10458 "use strict";
10459 var __extends = (this && this.__extends) || function (d, b) {
10460     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10461     function __() { this.constructor = d; }
10462     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10463 };
10464 var Subscriber_1 = require('../Subscriber');
10465 /**
10466  * Applies a given `project` function to each value emitted by the source
10467  * Observable, and emits the resulting values as an Observable.
10468  *
10469  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
10470  * it passes each source value through a transformation function to get
10471  * corresponding output values.</span>
10472  *
10473  * <img src="./img/map.png" width="100%">
10474  *
10475  * Similar to the well known `Array.prototype.map` function, this operator
10476  * applies a projection to each value and emits that projection in the output
10477  * Observable.
10478  *
10479  * @example <caption>Map every click to the clientX position of that click</caption>
10480  * var clicks = Rx.Observable.fromEvent(document, 'click');
10481  * var positions = clicks.map(ev => ev.clientX);
10482  * positions.subscribe(x => console.log(x));
10483  *
10484  * @see {@link mapTo}
10485  * @see {@link pluck}
10486  *
10487  * @param {function(value: T, index: number): R} project The function to apply
10488  * to each `value` emitted by the source Observable. The `index` parameter is
10489  * the number `i` for the i-th emission that has happened since the
10490  * subscription, starting from the number `0`.
10491  * @param {any} [thisArg] An optional argument to define what `this` is in the
10492  * `project` function.
10493  * @return {Observable<R>} An Observable that emits the values from the source
10494  * Observable transformed by the given `project` function.
10495  * @method map
10496  * @owner Observable
10497  */
10498 function map(project, thisArg) {
10499     if (typeof project !== 'function') {
10500         throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10501     }
10502     return this.lift(new MapOperator(project, thisArg));
10503 }
10504 exports.map = map;
10505 var MapOperator = (function () {
10506     function MapOperator(project, thisArg) {
10507         this.project = project;
10508         this.thisArg = thisArg;
10509     }
10510     MapOperator.prototype.call = function (subscriber, source) {
10511         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10512     };
10513     return MapOperator;
10514 }());
10515 exports.MapOperator = MapOperator;
10516 /**
10517  * We need this JSDoc comment for affecting ESDoc.
10518  * @ignore
10519  * @extends {Ignored}
10520  */
10521 var MapSubscriber = (function (_super) {
10522     __extends(MapSubscriber, _super);
10523     function MapSubscriber(destination, project, thisArg) {
10524         _super.call(this, destination);
10525         this.project = project;
10526         this.count = 0;
10527         this.thisArg = thisArg || this;
10528     }
10529     // NOTE: This looks unoptimized, but it's actually purposefully NOT
10530     // using try/catch optimizations.
10531     MapSubscriber.prototype._next = function (value) {
10532         var result;
10533         try {
10534             result = this.project.call(this.thisArg, value, this.count++);
10535         }
10536         catch (err) {
10537             this.destination.error(err);
10538             return;
10539         }
10540         this.destination.next(result);
10541     };
10542     return MapSubscriber;
10543 }(Subscriber_1.Subscriber));
10544
10545 },{"../Subscriber":36}],127:[function(require,module,exports){
10546 "use strict";
10547 var Observable_1 = require('../Observable');
10548 var ArrayObservable_1 = require('../observable/ArrayObservable');
10549 var mergeAll_1 = require('./mergeAll');
10550 var isScheduler_1 = require('../util/isScheduler');
10551 /* tslint:enable:max-line-length */
10552 /**
10553  * Creates an output Observable which concurrently emits all values from every
10554  * given input Observable.
10555  *
10556  * <span class="informal">Flattens multiple Observables together by blending
10557  * their values into one Observable.</span>
10558  *
10559  * <img src="./img/merge.png" width="100%">
10560  *
10561  * `merge` subscribes to each given input Observable (either the source or an
10562  * Observable given as argument), and simply forwards (without doing any
10563  * transformation) all the values from all the input Observables to the output
10564  * Observable. The output Observable only completes once all input Observables
10565  * have completed. Any error delivered by an input Observable will be immediately
10566  * emitted on the output Observable.
10567  *
10568  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10569  * var clicks = Rx.Observable.fromEvent(document, 'click');
10570  * var timer = Rx.Observable.interval(1000);
10571  * var clicksOrTimer = clicks.merge(timer);
10572  * clicksOrTimer.subscribe(x => console.log(x));
10573  *
10574  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10575  * var timer1 = Rx.Observable.interval(1000).take(10);
10576  * var timer2 = Rx.Observable.interval(2000).take(6);
10577  * var timer3 = Rx.Observable.interval(500).take(10);
10578  * var concurrent = 2; // the argument
10579  * var merged = timer1.merge(timer2, timer3, concurrent);
10580  * merged.subscribe(x => console.log(x));
10581  *
10582  * @see {@link mergeAll}
10583  * @see {@link mergeMap}
10584  * @see {@link mergeMapTo}
10585  * @see {@link mergeScan}
10586  *
10587  * @param {ObservableInput} other An input Observable to merge with the source
10588  * Observable. More than one input Observables may be given as argument.
10589  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10590  * Observables being subscribed to concurrently.
10591  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10592  * concurrency of input Observables.
10593  * @return {Observable} An Observable that emits items that are the result of
10594  * every input Observable.
10595  * @method merge
10596  * @owner Observable
10597  */
10598 function merge() {
10599     var observables = [];
10600     for (var _i = 0; _i < arguments.length; _i++) {
10601         observables[_i - 0] = arguments[_i];
10602     }
10603     return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
10604 }
10605 exports.merge = merge;
10606 /* tslint:enable:max-line-length */
10607 /**
10608  * Creates an output Observable which concurrently emits all values from every
10609  * given input Observable.
10610  *
10611  * <span class="informal">Flattens multiple Observables together by blending
10612  * their values into one Observable.</span>
10613  *
10614  * <img src="./img/merge.png" width="100%">
10615  *
10616  * `merge` subscribes to each given input Observable (as arguments), and simply
10617  * forwards (without doing any transformation) all the values from all the input
10618  * Observables to the output Observable. The output Observable only completes
10619  * once all input Observables have completed. Any error delivered by an input
10620  * Observable will be immediately emitted on the output Observable.
10621  *
10622  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10623  * var clicks = Rx.Observable.fromEvent(document, 'click');
10624  * var timer = Rx.Observable.interval(1000);
10625  * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
10626  * clicksOrTimer.subscribe(x => console.log(x));
10627  *
10628  * // Results in the following:
10629  * // timer will emit ascending values, one every second(1000ms) to console
10630  * // clicks logs MouseEvents to console everytime the "document" is clicked
10631  * // Since the two streams are merged you see these happening
10632  * // as they occur.
10633  *
10634  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10635  * var timer1 = Rx.Observable.interval(1000).take(10);
10636  * var timer2 = Rx.Observable.interval(2000).take(6);
10637  * var timer3 = Rx.Observable.interval(500).take(10);
10638  * var concurrent = 2; // the argument
10639  * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
10640  * merged.subscribe(x => console.log(x));
10641  *
10642  * // Results in the following:
10643  * // - First timer1 and timer2 will run concurrently
10644  * // - timer1 will emit a value every 1000ms for 10 iterations
10645  * // - timer2 will emit a value every 2000ms for 6 iterations
10646  * // - after timer1 hits it's max iteration, timer2 will
10647  * //   continue, and timer3 will start to run concurrently with timer2
10648  * // - when timer2 hits it's max iteration it terminates, and
10649  * //   timer3 will continue to emit a value every 500ms until it is complete
10650  *
10651  * @see {@link mergeAll}
10652  * @see {@link mergeMap}
10653  * @see {@link mergeMapTo}
10654  * @see {@link mergeScan}
10655  *
10656  * @param {...ObservableInput} observables Input Observables to merge together.
10657  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10658  * Observables being subscribed to concurrently.
10659  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10660  * concurrency of input Observables.
10661  * @return {Observable} an Observable that emits items that are the result of
10662  * every input Observable.
10663  * @static true
10664  * @name merge
10665  * @owner Observable
10666  */
10667 function mergeStatic() {
10668     var observables = [];
10669     for (var _i = 0; _i < arguments.length; _i++) {
10670         observables[_i - 0] = arguments[_i];
10671     }
10672     var concurrent = Number.POSITIVE_INFINITY;
10673     var scheduler = null;
10674     var last = observables[observables.length - 1];
10675     if (isScheduler_1.isScheduler(last)) {
10676         scheduler = observables.pop();
10677         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
10678             concurrent = observables.pop();
10679         }
10680     }
10681     else if (typeof last === 'number') {
10682         concurrent = observables.pop();
10683     }
10684     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
10685         return observables[0];
10686     }
10687     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
10688 }
10689 exports.mergeStatic = mergeStatic;
10690
10691 },{"../Observable":29,"../observable/ArrayObservable":88,"../util/isScheduler":175,"./mergeAll":128}],128:[function(require,module,exports){
10692 "use strict";
10693 var __extends = (this && this.__extends) || function (d, b) {
10694     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10695     function __() { this.constructor = d; }
10696     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10697 };
10698 var OuterSubscriber_1 = require('../OuterSubscriber');
10699 var subscribeToResult_1 = require('../util/subscribeToResult');
10700 /**
10701  * Converts a higher-order Observable into a first-order Observable which
10702  * concurrently delivers all values that are emitted on the inner Observables.
10703  *
10704  * <span class="informal">Flattens an Observable-of-Observables.</span>
10705  *
10706  * <img src="./img/mergeAll.png" width="100%">
10707  *
10708  * `mergeAll` subscribes to an Observable that emits Observables, also known as
10709  * a higher-order Observable. Each time it observes one of these emitted inner
10710  * Observables, it subscribes to that and delivers all the values from the
10711  * inner Observable on the output Observable. The output Observable only
10712  * completes once all inner Observables have completed. Any error delivered by
10713  * a inner Observable will be immediately emitted on the output Observable.
10714  *
10715  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
10716  * var clicks = Rx.Observable.fromEvent(document, 'click');
10717  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
10718  * var firstOrder = higherOrder.mergeAll();
10719  * firstOrder.subscribe(x => console.log(x));
10720  *
10721  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
10722  * var clicks = Rx.Observable.fromEvent(document, 'click');
10723  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
10724  * var firstOrder = higherOrder.mergeAll(2);
10725  * firstOrder.subscribe(x => console.log(x));
10726  *
10727  * @see {@link combineAll}
10728  * @see {@link concatAll}
10729  * @see {@link exhaust}
10730  * @see {@link merge}
10731  * @see {@link mergeMap}
10732  * @see {@link mergeMapTo}
10733  * @see {@link mergeScan}
10734  * @see {@link switch}
10735  * @see {@link zipAll}
10736  *
10737  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
10738  * Observables being subscribed to concurrently.
10739  * @return {Observable} An Observable that emits values coming from all the
10740  * inner Observables emitted by the source Observable.
10741  * @method mergeAll
10742  * @owner Observable
10743  */
10744 function mergeAll(concurrent) {
10745     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10746     return this.lift(new MergeAllOperator(concurrent));
10747 }
10748 exports.mergeAll = mergeAll;
10749 var MergeAllOperator = (function () {
10750     function MergeAllOperator(concurrent) {
10751         this.concurrent = concurrent;
10752     }
10753     MergeAllOperator.prototype.call = function (observer, source) {
10754         return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
10755     };
10756     return MergeAllOperator;
10757 }());
10758 exports.MergeAllOperator = MergeAllOperator;
10759 /**
10760  * We need this JSDoc comment for affecting ESDoc.
10761  * @ignore
10762  * @extends {Ignored}
10763  */
10764 var MergeAllSubscriber = (function (_super) {
10765     __extends(MergeAllSubscriber, _super);
10766     function MergeAllSubscriber(destination, concurrent) {
10767         _super.call(this, destination);
10768         this.concurrent = concurrent;
10769         this.hasCompleted = false;
10770         this.buffer = [];
10771         this.active = 0;
10772     }
10773     MergeAllSubscriber.prototype._next = function (observable) {
10774         if (this.active < this.concurrent) {
10775             this.active++;
10776             this.add(subscribeToResult_1.subscribeToResult(this, observable));
10777         }
10778         else {
10779             this.buffer.push(observable);
10780         }
10781     };
10782     MergeAllSubscriber.prototype._complete = function () {
10783         this.hasCompleted = true;
10784         if (this.active === 0 && this.buffer.length === 0) {
10785             this.destination.complete();
10786         }
10787     };
10788     MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
10789         var buffer = this.buffer;
10790         this.remove(innerSub);
10791         this.active--;
10792         if (buffer.length > 0) {
10793             this._next(buffer.shift());
10794         }
10795         else if (this.active === 0 && this.hasCompleted) {
10796             this.destination.complete();
10797         }
10798     };
10799     return MergeAllSubscriber;
10800 }(OuterSubscriber_1.OuterSubscriber));
10801 exports.MergeAllSubscriber = MergeAllSubscriber;
10802
10803 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],129:[function(require,module,exports){
10804 "use strict";
10805 var __extends = (this && this.__extends) || function (d, b) {
10806     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10807     function __() { this.constructor = d; }
10808     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10809 };
10810 var subscribeToResult_1 = require('../util/subscribeToResult');
10811 var OuterSubscriber_1 = require('../OuterSubscriber');
10812 /* tslint:enable:max-line-length */
10813 /**
10814  * Projects each source value to an Observable which is merged in the output
10815  * Observable.
10816  *
10817  * <span class="informal">Maps each value to an Observable, then flattens all of
10818  * these inner Observables using {@link mergeAll}.</span>
10819  *
10820  * <img src="./img/mergeMap.png" width="100%">
10821  *
10822  * Returns an Observable that emits items based on applying a function that you
10823  * supply to each item emitted by the source Observable, where that function
10824  * returns an Observable, and then merging those resulting Observables and
10825  * emitting the results of this merger.
10826  *
10827  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10828  * var letters = Rx.Observable.of('a', 'b', 'c');
10829  * var result = letters.mergeMap(x =>
10830  *   Rx.Observable.interval(1000).map(i => x+i)
10831  * );
10832  * result.subscribe(x => console.log(x));
10833  *
10834  * // Results in the following:
10835  * // a0
10836  * // b0
10837  * // c0
10838  * // a1
10839  * // b1
10840  * // c1
10841  * // continues to list a,b,c with respective ascending integers
10842  *
10843  * @see {@link concatMap}
10844  * @see {@link exhaustMap}
10845  * @see {@link merge}
10846  * @see {@link mergeAll}
10847  * @see {@link mergeMapTo}
10848  * @see {@link mergeScan}
10849  * @see {@link switchMap}
10850  *
10851  * @param {function(value: T, ?index: number): ObservableInput} project A function
10852  * that, when applied to an item emitted by the source Observable, returns an
10853  * Observable.
10854  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10855  * A function to produce the value on the output Observable based on the values
10856  * and the indices of the source (outer) emission and the inner Observable
10857  * emission. The arguments passed to this function are:
10858  * - `outerValue`: the value that came from the source
10859  * - `innerValue`: the value that came from the projected Observable
10860  * - `outerIndex`: the "index" of the value that came from the source
10861  * - `innerIndex`: the "index" of the value from the projected Observable
10862  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10863  * Observables being subscribed to concurrently.
10864  * @return {Observable} An Observable that emits the result of applying the
10865  * projection function (and the optional `resultSelector`) to each item emitted
10866  * by the source Observable and merging the results of the Observables obtained
10867  * from this transformation.
10868  * @method mergeMap
10869  * @owner Observable
10870  */
10871 function mergeMap(project, resultSelector, concurrent) {
10872     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10873     if (typeof resultSelector === 'number') {
10874         concurrent = resultSelector;
10875         resultSelector = null;
10876     }
10877     return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10878 }
10879 exports.mergeMap = mergeMap;
10880 var MergeMapOperator = (function () {
10881     function MergeMapOperator(project, resultSelector, concurrent) {
10882         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10883         this.project = project;
10884         this.resultSelector = resultSelector;
10885         this.concurrent = concurrent;
10886     }
10887     MergeMapOperator.prototype.call = function (observer, source) {
10888         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10889     };
10890     return MergeMapOperator;
10891 }());
10892 exports.MergeMapOperator = MergeMapOperator;
10893 /**
10894  * We need this JSDoc comment for affecting ESDoc.
10895  * @ignore
10896  * @extends {Ignored}
10897  */
10898 var MergeMapSubscriber = (function (_super) {
10899     __extends(MergeMapSubscriber, _super);
10900     function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10901         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10902         _super.call(this, destination);
10903         this.project = project;
10904         this.resultSelector = resultSelector;
10905         this.concurrent = concurrent;
10906         this.hasCompleted = false;
10907         this.buffer = [];
10908         this.active = 0;
10909         this.index = 0;
10910     }
10911     MergeMapSubscriber.prototype._next = function (value) {
10912         if (this.active < this.concurrent) {
10913             this._tryNext(value);
10914         }
10915         else {
10916             this.buffer.push(value);
10917         }
10918     };
10919     MergeMapSubscriber.prototype._tryNext = function (value) {
10920         var result;
10921         var index = this.index++;
10922         try {
10923             result = this.project(value, index);
10924         }
10925         catch (err) {
10926             this.destination.error(err);
10927             return;
10928         }
10929         this.active++;
10930         this._innerSub(result, value, index);
10931     };
10932     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10933         this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10934     };
10935     MergeMapSubscriber.prototype._complete = function () {
10936         this.hasCompleted = true;
10937         if (this.active === 0 && this.buffer.length === 0) {
10938             this.destination.complete();
10939         }
10940     };
10941     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10942         if (this.resultSelector) {
10943             this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10944         }
10945         else {
10946             this.destination.next(innerValue);
10947         }
10948     };
10949     MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10950         var result;
10951         try {
10952             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10953         }
10954         catch (err) {
10955             this.destination.error(err);
10956             return;
10957         }
10958         this.destination.next(result);
10959     };
10960     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10961         var buffer = this.buffer;
10962         this.remove(innerSub);
10963         this.active--;
10964         if (buffer.length > 0) {
10965             this._next(buffer.shift());
10966         }
10967         else if (this.active === 0 && this.hasCompleted) {
10968             this.destination.complete();
10969         }
10970     };
10971     return MergeMapSubscriber;
10972 }(OuterSubscriber_1.OuterSubscriber));
10973 exports.MergeMapSubscriber = MergeMapSubscriber;
10974
10975 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],130:[function(require,module,exports){
10976 "use strict";
10977 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10978 /* tslint:enable:max-line-length */
10979 /**
10980  * Returns an Observable that emits the results of invoking a specified selector on items
10981  * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10982  *
10983  * <img src="./img/multicast.png" width="100%">
10984  *
10985  * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
10986  * which the source sequence's elements will be multicast to the selector function
10987  * or Subject to push source elements into.
10988  * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
10989  * as many times as needed, without causing multiple subscriptions to the source stream.
10990  * Subscribers to the given source will receive all notifications of the source from the
10991  * time of the subscription forward.
10992  * @return {Observable} An Observable that emits the results of invoking the selector
10993  * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10994  * the underlying stream.
10995  * @method multicast
10996  * @owner Observable
10997  */
10998 function multicast(subjectOrSubjectFactory, selector) {
10999     var subjectFactory;
11000     if (typeof subjectOrSubjectFactory === 'function') {
11001         subjectFactory = subjectOrSubjectFactory;
11002     }
11003     else {
11004         subjectFactory = function subjectFactory() {
11005             return subjectOrSubjectFactory;
11006         };
11007     }
11008     if (typeof selector === 'function') {
11009         return this.lift(new MulticastOperator(subjectFactory, selector));
11010     }
11011     var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
11012     connectable.source = this;
11013     connectable.subjectFactory = subjectFactory;
11014     return connectable;
11015 }
11016 exports.multicast = multicast;
11017 var MulticastOperator = (function () {
11018     function MulticastOperator(subjectFactory, selector) {
11019         this.subjectFactory = subjectFactory;
11020         this.selector = selector;
11021     }
11022     MulticastOperator.prototype.call = function (subscriber, source) {
11023         var selector = this.selector;
11024         var subject = this.subjectFactory();
11025         var subscription = selector(subject).subscribe(subscriber);
11026         subscription.add(source.subscribe(subject));
11027         return subscription;
11028     };
11029     return MulticastOperator;
11030 }());
11031 exports.MulticastOperator = MulticastOperator;
11032
11033 },{"../observable/ConnectableObservable":89}],131:[function(require,module,exports){
11034 "use strict";
11035 var __extends = (this && this.__extends) || function (d, b) {
11036     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11037     function __() { this.constructor = d; }
11038     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11039 };
11040 var Subscriber_1 = require('../Subscriber');
11041 var Notification_1 = require('../Notification');
11042 /**
11043  *
11044  * Re-emits all notifications from source Observable with specified scheduler.
11045  *
11046  * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
11047  *
11048  * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
11049  * notifications emitted by the source Observable. It might be useful, if you do not have control over
11050  * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
11051  *
11052  * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
11053  * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
11054  * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
11055  * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
11056  * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
11057  * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
11058  * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
11059  * little bit more, to ensure that they are emitted at expected moments.
11060  *
11061  * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
11062  * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
11063  * will delay all notifications - including error notifications - while `delay` will pass through error
11064  * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
11065  * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
11066  * for notification emissions in general.
11067  *
11068  * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
11069  * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
11070  *                                               // with async scheduler by default...
11071  *
11072  * intervals
11073  * .observeOn(Rx.Scheduler.animationFrame)       // ...but we will observe on animationFrame
11074  * .subscribe(val => {                           // scheduler to ensure smooth animation.
11075  *   someDiv.style.height = val + 'px';
11076  * });
11077  *
11078  * @see {@link delay}
11079  *
11080  * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
11081  * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
11082  * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
11083  * but with provided scheduler.
11084  *
11085  * @method observeOn
11086  * @owner Observable
11087  */
11088 function observeOn(scheduler, delay) {
11089     if (delay === void 0) { delay = 0; }
11090     return this.lift(new ObserveOnOperator(scheduler, delay));
11091 }
11092 exports.observeOn = observeOn;
11093 var ObserveOnOperator = (function () {
11094     function ObserveOnOperator(scheduler, delay) {
11095         if (delay === void 0) { delay = 0; }
11096         this.scheduler = scheduler;
11097         this.delay = delay;
11098     }
11099     ObserveOnOperator.prototype.call = function (subscriber, source) {
11100         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
11101     };
11102     return ObserveOnOperator;
11103 }());
11104 exports.ObserveOnOperator = ObserveOnOperator;
11105 /**
11106  * We need this JSDoc comment for affecting ESDoc.
11107  * @ignore
11108  * @extends {Ignored}
11109  */
11110 var ObserveOnSubscriber = (function (_super) {
11111     __extends(ObserveOnSubscriber, _super);
11112     function ObserveOnSubscriber(destination, scheduler, delay) {
11113         if (delay === void 0) { delay = 0; }
11114         _super.call(this, destination);
11115         this.scheduler = scheduler;
11116         this.delay = delay;
11117     }
11118     ObserveOnSubscriber.dispatch = function (arg) {
11119         var notification = arg.notification, destination = arg.destination;
11120         notification.observe(destination);
11121         this.unsubscribe();
11122     };
11123     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
11124         this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
11125     };
11126     ObserveOnSubscriber.prototype._next = function (value) {
11127         this.scheduleMessage(Notification_1.Notification.createNext(value));
11128     };
11129     ObserveOnSubscriber.prototype._error = function (err) {
11130         this.scheduleMessage(Notification_1.Notification.createError(err));
11131     };
11132     ObserveOnSubscriber.prototype._complete = function () {
11133         this.scheduleMessage(Notification_1.Notification.createComplete());
11134     };
11135     return ObserveOnSubscriber;
11136 }(Subscriber_1.Subscriber));
11137 exports.ObserveOnSubscriber = ObserveOnSubscriber;
11138 var ObserveOnMessage = (function () {
11139     function ObserveOnMessage(notification, destination) {
11140         this.notification = notification;
11141         this.destination = destination;
11142     }
11143     return ObserveOnMessage;
11144 }());
11145 exports.ObserveOnMessage = ObserveOnMessage;
11146
11147 },{"../Notification":28,"../Subscriber":36}],132:[function(require,module,exports){
11148 "use strict";
11149 var __extends = (this && this.__extends) || function (d, b) {
11150     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11151     function __() { this.constructor = d; }
11152     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11153 };
11154 var Subscriber_1 = require('../Subscriber');
11155 /**
11156  * Groups pairs of consecutive emissions together and emits them as an array of
11157  * two values.
11158  *
11159  * <span class="informal">Puts the current value and previous value together as
11160  * an array, and emits that.</span>
11161  *
11162  * <img src="./img/pairwise.png" width="100%">
11163  *
11164  * The Nth emission from the source Observable will cause the output Observable
11165  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
11166  * pair. For this reason, `pairwise` emits on the second and subsequent
11167  * emissions from the source Observable, but not on the first emission, because
11168  * there is no previous value in that case.
11169  *
11170  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
11171  * var clicks = Rx.Observable.fromEvent(document, 'click');
11172  * var pairs = clicks.pairwise();
11173  * var distance = pairs.map(pair => {
11174  *   var x0 = pair[0].clientX;
11175  *   var y0 = pair[0].clientY;
11176  *   var x1 = pair[1].clientX;
11177  *   var y1 = pair[1].clientY;
11178  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
11179  * });
11180  * distance.subscribe(x => console.log(x));
11181  *
11182  * @see {@link buffer}
11183  * @see {@link bufferCount}
11184  *
11185  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
11186  * consecutive values from the source Observable.
11187  * @method pairwise
11188  * @owner Observable
11189  */
11190 function pairwise() {
11191     return this.lift(new PairwiseOperator());
11192 }
11193 exports.pairwise = pairwise;
11194 var PairwiseOperator = (function () {
11195     function PairwiseOperator() {
11196     }
11197     PairwiseOperator.prototype.call = function (subscriber, source) {
11198         return source.subscribe(new PairwiseSubscriber(subscriber));
11199     };
11200     return PairwiseOperator;
11201 }());
11202 /**
11203  * We need this JSDoc comment for affecting ESDoc.
11204  * @ignore
11205  * @extends {Ignored}
11206  */
11207 var PairwiseSubscriber = (function (_super) {
11208     __extends(PairwiseSubscriber, _super);
11209     function PairwiseSubscriber(destination) {
11210         _super.call(this, destination);
11211         this.hasPrev = false;
11212     }
11213     PairwiseSubscriber.prototype._next = function (value) {
11214         if (this.hasPrev) {
11215             this.destination.next([this.prev, value]);
11216         }
11217         else {
11218             this.hasPrev = true;
11219         }
11220         this.prev = value;
11221     };
11222     return PairwiseSubscriber;
11223 }(Subscriber_1.Subscriber));
11224
11225 },{"../Subscriber":36}],133:[function(require,module,exports){
11226 "use strict";
11227 var map_1 = require('./map');
11228 /**
11229  * Maps each source value (an object) to its specified nested property.
11230  *
11231  * <span class="informal">Like {@link map}, but meant only for picking one of
11232  * the nested properties of every emitted object.</span>
11233  *
11234  * <img src="./img/pluck.png" width="100%">
11235  *
11236  * Given a list of strings describing a path to an object property, retrieves
11237  * the value of a specified nested property from all values in the source
11238  * Observable. If a property can't be resolved, it will return `undefined` for
11239  * that value.
11240  *
11241  * @example <caption>Map every click to the tagName of the clicked target element</caption>
11242  * var clicks = Rx.Observable.fromEvent(document, 'click');
11243  * var tagNames = clicks.pluck('target', 'tagName');
11244  * tagNames.subscribe(x => console.log(x));
11245  *
11246  * @see {@link map}
11247  *
11248  * @param {...string} properties The nested properties to pluck from each source
11249  * value (an object).
11250  * @return {Observable} A new Observable of property values from the source values.
11251  * @method pluck
11252  * @owner Observable
11253  */
11254 function pluck() {
11255     var properties = [];
11256     for (var _i = 0; _i < arguments.length; _i++) {
11257         properties[_i - 0] = arguments[_i];
11258     }
11259     var length = properties.length;
11260     if (length === 0) {
11261         throw new Error('list of properties cannot be empty.');
11262     }
11263     return map_1.map.call(this, plucker(properties, length));
11264 }
11265 exports.pluck = pluck;
11266 function plucker(props, length) {
11267     var mapper = function (x) {
11268         var currentProp = x;
11269         for (var i = 0; i < length; i++) {
11270             var p = currentProp[props[i]];
11271             if (typeof p !== 'undefined') {
11272                 currentProp = p;
11273             }
11274             else {
11275                 return undefined;
11276             }
11277         }
11278         return currentProp;
11279     };
11280     return mapper;
11281 }
11282
11283 },{"./map":126}],134:[function(require,module,exports){
11284 "use strict";
11285 var Subject_1 = require('../Subject');
11286 var multicast_1 = require('./multicast');
11287 /* tslint:enable:max-line-length */
11288 /**
11289  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
11290  * before it begins emitting items to those Observers that have subscribed to it.
11291  *
11292  * <img src="./img/publish.png" width="100%">
11293  *
11294  * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
11295  * as needed, without causing multiple subscriptions to the source sequence.
11296  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
11297  * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
11298  * @method publish
11299  * @owner Observable
11300  */
11301 function publish(selector) {
11302     return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
11303         multicast_1.multicast.call(this, new Subject_1.Subject());
11304 }
11305 exports.publish = publish;
11306
11307 },{"../Subject":34,"./multicast":130}],135:[function(require,module,exports){
11308 "use strict";
11309 var ReplaySubject_1 = require('../ReplaySubject');
11310 var multicast_1 = require('./multicast');
11311 /**
11312  * @param bufferSize
11313  * @param windowTime
11314  * @param scheduler
11315  * @return {ConnectableObservable<T>}
11316  * @method publishReplay
11317  * @owner Observable
11318  */
11319 function publishReplay(bufferSize, windowTime, scheduler) {
11320     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
11321     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
11322     return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
11323 }
11324 exports.publishReplay = publishReplay;
11325
11326 },{"../ReplaySubject":32,"./multicast":130}],136:[function(require,module,exports){
11327 "use strict";
11328 var __extends = (this && this.__extends) || function (d, b) {
11329     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11330     function __() { this.constructor = d; }
11331     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11332 };
11333 var OuterSubscriber_1 = require('../OuterSubscriber');
11334 var subscribeToResult_1 = require('../util/subscribeToResult');
11335 /**
11336  * Emits the most recently emitted value from the source Observable whenever
11337  * another Observable, the `notifier`, emits.
11338  *
11339  * <span class="informal">It's like {@link sampleTime}, but samples whenever
11340  * the `notifier` Observable emits something.</span>
11341  *
11342  * <img src="./img/sample.png" width="100%">
11343  *
11344  * Whenever the `notifier` Observable emits a value or completes, `sample`
11345  * looks at the source Observable and emits whichever value it has most recently
11346  * emitted since the previous sampling, unless the source has not emitted
11347  * anything since the previous sampling. The `notifier` is subscribed to as soon
11348  * as the output Observable is subscribed.
11349  *
11350  * @example <caption>On every click, sample the most recent "seconds" timer</caption>
11351  * var seconds = Rx.Observable.interval(1000);
11352  * var clicks = Rx.Observable.fromEvent(document, 'click');
11353  * var result = seconds.sample(clicks);
11354  * result.subscribe(x => console.log(x));
11355  *
11356  * @see {@link audit}
11357  * @see {@link debounce}
11358  * @see {@link sampleTime}
11359  * @see {@link throttle}
11360  *
11361  * @param {Observable<any>} notifier The Observable to use for sampling the
11362  * source Observable.
11363  * @return {Observable<T>} An Observable that emits the results of sampling the
11364  * values emitted by the source Observable whenever the notifier Observable
11365  * emits value or completes.
11366  * @method sample
11367  * @owner Observable
11368  */
11369 function sample(notifier) {
11370     return this.lift(new SampleOperator(notifier));
11371 }
11372 exports.sample = sample;
11373 var SampleOperator = (function () {
11374     function SampleOperator(notifier) {
11375         this.notifier = notifier;
11376     }
11377     SampleOperator.prototype.call = function (subscriber, source) {
11378         var sampleSubscriber = new SampleSubscriber(subscriber);
11379         var subscription = source.subscribe(sampleSubscriber);
11380         subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
11381         return subscription;
11382     };
11383     return SampleOperator;
11384 }());
11385 /**
11386  * We need this JSDoc comment for affecting ESDoc.
11387  * @ignore
11388  * @extends {Ignored}
11389  */
11390 var SampleSubscriber = (function (_super) {
11391     __extends(SampleSubscriber, _super);
11392     function SampleSubscriber() {
11393         _super.apply(this, arguments);
11394         this.hasValue = false;
11395     }
11396     SampleSubscriber.prototype._next = function (value) {
11397         this.value = value;
11398         this.hasValue = true;
11399     };
11400     SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11401         this.emitValue();
11402     };
11403     SampleSubscriber.prototype.notifyComplete = function () {
11404         this.emitValue();
11405     };
11406     SampleSubscriber.prototype.emitValue = function () {
11407         if (this.hasValue) {
11408             this.hasValue = false;
11409             this.destination.next(this.value);
11410         }
11411     };
11412     return SampleSubscriber;
11413 }(OuterSubscriber_1.OuterSubscriber));
11414
11415 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],137:[function(require,module,exports){
11416 "use strict";
11417 var __extends = (this && this.__extends) || function (d, b) {
11418     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11419     function __() { this.constructor = d; }
11420     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11421 };
11422 var Subscriber_1 = require('../Subscriber');
11423 /* tslint:enable:max-line-length */
11424 /**
11425  * Applies an accumulator function over the source Observable, and returns each
11426  * intermediate result, with an optional seed value.
11427  *
11428  * <span class="informal">It's like {@link reduce}, but emits the current
11429  * accumulation whenever the source emits a value.</span>
11430  *
11431  * <img src="./img/scan.png" width="100%">
11432  *
11433  * Combines together all values emitted on the source, using an accumulator
11434  * function that knows how to join a new source value into the accumulation from
11435  * the past. Is similar to {@link reduce}, but emits the intermediate
11436  * accumulations.
11437  *
11438  * Returns an Observable that applies a specified `accumulator` function to each
11439  * item emitted by the source Observable. If a `seed` value is specified, then
11440  * that value will be used as the initial value for the accumulator. If no seed
11441  * value is specified, the first item of the source is used as the seed.
11442  *
11443  * @example <caption>Count the number of click events</caption>
11444  * var clicks = Rx.Observable.fromEvent(document, 'click');
11445  * var ones = clicks.mapTo(1);
11446  * var seed = 0;
11447  * var count = ones.scan((acc, one) => acc + one, seed);
11448  * count.subscribe(x => console.log(x));
11449  *
11450  * @see {@link expand}
11451  * @see {@link mergeScan}
11452  * @see {@link reduce}
11453  *
11454  * @param {function(acc: R, value: T, index: number): R} accumulator
11455  * The accumulator function called on each source value.
11456  * @param {T|R} [seed] The initial accumulation value.
11457  * @return {Observable<R>} An observable of the accumulated values.
11458  * @method scan
11459  * @owner Observable
11460  */
11461 function scan(accumulator, seed) {
11462     var hasSeed = false;
11463     // providing a seed of `undefined` *should* be valid and trigger
11464     // hasSeed! so don't use `seed !== undefined` checks!
11465     // For this reason, we have to check it here at the original call site
11466     // otherwise inside Operator/Subscriber we won't know if `undefined`
11467     // means they didn't provide anything or if they literally provided `undefined`
11468     if (arguments.length >= 2) {
11469         hasSeed = true;
11470     }
11471     return this.lift(new ScanOperator(accumulator, seed, hasSeed));
11472 }
11473 exports.scan = scan;
11474 var ScanOperator = (function () {
11475     function ScanOperator(accumulator, seed, hasSeed) {
11476         if (hasSeed === void 0) { hasSeed = false; }
11477         this.accumulator = accumulator;
11478         this.seed = seed;
11479         this.hasSeed = hasSeed;
11480     }
11481     ScanOperator.prototype.call = function (subscriber, source) {
11482         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
11483     };
11484     return ScanOperator;
11485 }());
11486 /**
11487  * We need this JSDoc comment for affecting ESDoc.
11488  * @ignore
11489  * @extends {Ignored}
11490  */
11491 var ScanSubscriber = (function (_super) {
11492     __extends(ScanSubscriber, _super);
11493     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
11494         _super.call(this, destination);
11495         this.accumulator = accumulator;
11496         this._seed = _seed;
11497         this.hasSeed = hasSeed;
11498         this.index = 0;
11499     }
11500     Object.defineProperty(ScanSubscriber.prototype, "seed", {
11501         get: function () {
11502             return this._seed;
11503         },
11504         set: function (value) {
11505             this.hasSeed = true;
11506             this._seed = value;
11507         },
11508         enumerable: true,
11509         configurable: true
11510     });
11511     ScanSubscriber.prototype._next = function (value) {
11512         if (!this.hasSeed) {
11513             this.seed = value;
11514             this.destination.next(value);
11515         }
11516         else {
11517             return this._tryNext(value);
11518         }
11519     };
11520     ScanSubscriber.prototype._tryNext = function (value) {
11521         var index = this.index++;
11522         var result;
11523         try {
11524             result = this.accumulator(this.seed, value, index);
11525         }
11526         catch (err) {
11527             this.destination.error(err);
11528         }
11529         this.seed = result;
11530         this.destination.next(result);
11531     };
11532     return ScanSubscriber;
11533 }(Subscriber_1.Subscriber));
11534
11535 },{"../Subscriber":36}],138:[function(require,module,exports){
11536 "use strict";
11537 var multicast_1 = require('./multicast');
11538 var Subject_1 = require('../Subject');
11539 function shareSubjectFactory() {
11540     return new Subject_1.Subject();
11541 }
11542 /**
11543  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
11544  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
11545  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
11546  * This is an alias for .publish().refCount().
11547  *
11548  * <img src="./img/share.png" width="100%">
11549  *
11550  * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
11551  * @method share
11552  * @owner Observable
11553  */
11554 function share() {
11555     return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
11556 }
11557 exports.share = share;
11558 ;
11559
11560 },{"../Subject":34,"./multicast":130}],139:[function(require,module,exports){
11561 "use strict";
11562 var __extends = (this && this.__extends) || function (d, b) {
11563     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11564     function __() { this.constructor = d; }
11565     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11566 };
11567 var Subscriber_1 = require('../Subscriber');
11568 /**
11569  * Returns an Observable that skips the first `count` items emitted by the source Observable.
11570  *
11571  * <img src="./img/skip.png" width="100%">
11572  *
11573  * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
11574  * @return {Observable} An Observable that skips values emitted by the source Observable.
11575  *
11576  * @method skip
11577  * @owner Observable
11578  */
11579 function skip(count) {
11580     return this.lift(new SkipOperator(count));
11581 }
11582 exports.skip = skip;
11583 var SkipOperator = (function () {
11584     function SkipOperator(total) {
11585         this.total = total;
11586     }
11587     SkipOperator.prototype.call = function (subscriber, source) {
11588         return source.subscribe(new SkipSubscriber(subscriber, this.total));
11589     };
11590     return SkipOperator;
11591 }());
11592 /**
11593  * We need this JSDoc comment for affecting ESDoc.
11594  * @ignore
11595  * @extends {Ignored}
11596  */
11597 var SkipSubscriber = (function (_super) {
11598     __extends(SkipSubscriber, _super);
11599     function SkipSubscriber(destination, total) {
11600         _super.call(this, destination);
11601         this.total = total;
11602         this.count = 0;
11603     }
11604     SkipSubscriber.prototype._next = function (x) {
11605         if (++this.count > this.total) {
11606             this.destination.next(x);
11607         }
11608     };
11609     return SkipSubscriber;
11610 }(Subscriber_1.Subscriber));
11611
11612 },{"../Subscriber":36}],140:[function(require,module,exports){
11613 "use strict";
11614 var __extends = (this && this.__extends) || function (d, b) {
11615     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11616     function __() { this.constructor = d; }
11617     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11618 };
11619 var OuterSubscriber_1 = require('../OuterSubscriber');
11620 var subscribeToResult_1 = require('../util/subscribeToResult');
11621 /**
11622  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
11623  *
11624  * <img src="./img/skipUntil.png" width="100%">
11625  *
11626  * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
11627  * be mirrored by the resulting Observable.
11628  * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
11629  * an item, then emits the remaining items.
11630  * @method skipUntil
11631  * @owner Observable
11632  */
11633 function skipUntil(notifier) {
11634     return this.lift(new SkipUntilOperator(notifier));
11635 }
11636 exports.skipUntil = skipUntil;
11637 var SkipUntilOperator = (function () {
11638     function SkipUntilOperator(notifier) {
11639         this.notifier = notifier;
11640     }
11641     SkipUntilOperator.prototype.call = function (subscriber, source) {
11642         return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
11643     };
11644     return SkipUntilOperator;
11645 }());
11646 /**
11647  * We need this JSDoc comment for affecting ESDoc.
11648  * @ignore
11649  * @extends {Ignored}
11650  */
11651 var SkipUntilSubscriber = (function (_super) {
11652     __extends(SkipUntilSubscriber, _super);
11653     function SkipUntilSubscriber(destination, notifier) {
11654         _super.call(this, destination);
11655         this.hasValue = false;
11656         this.isInnerStopped = false;
11657         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11658     }
11659     SkipUntilSubscriber.prototype._next = function (value) {
11660         if (this.hasValue) {
11661             _super.prototype._next.call(this, value);
11662         }
11663     };
11664     SkipUntilSubscriber.prototype._complete = function () {
11665         if (this.isInnerStopped) {
11666             _super.prototype._complete.call(this);
11667         }
11668         else {
11669             this.unsubscribe();
11670         }
11671     };
11672     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11673         this.hasValue = true;
11674     };
11675     SkipUntilSubscriber.prototype.notifyComplete = function () {
11676         this.isInnerStopped = true;
11677         if (this.isStopped) {
11678             _super.prototype._complete.call(this);
11679         }
11680     };
11681     return SkipUntilSubscriber;
11682 }(OuterSubscriber_1.OuterSubscriber));
11683
11684 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],141:[function(require,module,exports){
11685 "use strict";
11686 var __extends = (this && this.__extends) || function (d, b) {
11687     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11688     function __() { this.constructor = d; }
11689     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11690 };
11691 var Subscriber_1 = require('../Subscriber');
11692 /**
11693  * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
11694  * true, but emits all further source items as soon as the condition becomes false.
11695  *
11696  * <img src="./img/skipWhile.png" width="100%">
11697  *
11698  * @param {Function} predicate - A function to test each item emitted from the source Observable.
11699  * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
11700  * specified predicate becomes false.
11701  * @method skipWhile
11702  * @owner Observable
11703  */
11704 function skipWhile(predicate) {
11705     return this.lift(new SkipWhileOperator(predicate));
11706 }
11707 exports.skipWhile = skipWhile;
11708 var SkipWhileOperator = (function () {
11709     function SkipWhileOperator(predicate) {
11710         this.predicate = predicate;
11711     }
11712     SkipWhileOperator.prototype.call = function (subscriber, source) {
11713         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
11714     };
11715     return SkipWhileOperator;
11716 }());
11717 /**
11718  * We need this JSDoc comment for affecting ESDoc.
11719  * @ignore
11720  * @extends {Ignored}
11721  */
11722 var SkipWhileSubscriber = (function (_super) {
11723     __extends(SkipWhileSubscriber, _super);
11724     function SkipWhileSubscriber(destination, predicate) {
11725         _super.call(this, destination);
11726         this.predicate = predicate;
11727         this.skipping = true;
11728         this.index = 0;
11729     }
11730     SkipWhileSubscriber.prototype._next = function (value) {
11731         var destination = this.destination;
11732         if (this.skipping) {
11733             this.tryCallPredicate(value);
11734         }
11735         if (!this.skipping) {
11736             destination.next(value);
11737         }
11738     };
11739     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
11740         try {
11741             var result = this.predicate(value, this.index++);
11742             this.skipping = Boolean(result);
11743         }
11744         catch (err) {
11745             this.destination.error(err);
11746         }
11747     };
11748     return SkipWhileSubscriber;
11749 }(Subscriber_1.Subscriber));
11750
11751 },{"../Subscriber":36}],142:[function(require,module,exports){
11752 "use strict";
11753 var ArrayObservable_1 = require('../observable/ArrayObservable');
11754 var ScalarObservable_1 = require('../observable/ScalarObservable');
11755 var EmptyObservable_1 = require('../observable/EmptyObservable');
11756 var concat_1 = require('./concat');
11757 var isScheduler_1 = require('../util/isScheduler');
11758 /* tslint:enable:max-line-length */
11759 /**
11760  * Returns an Observable that emits the items you specify as arguments before it begins to emit
11761  * items emitted by the source Observable.
11762  *
11763  * <img src="./img/startWith.png" width="100%">
11764  *
11765  * @param {...T} values - Items you want the modified Observable to emit first.
11766  * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
11767  * the emissions of the `next` notifications.
11768  * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
11769  * emitted by the source Observable.
11770  * @method startWith
11771  * @owner Observable
11772  */
11773 function startWith() {
11774     var array = [];
11775     for (var _i = 0; _i < arguments.length; _i++) {
11776         array[_i - 0] = arguments[_i];
11777     }
11778     var scheduler = array[array.length - 1];
11779     if (isScheduler_1.isScheduler(scheduler)) {
11780         array.pop();
11781     }
11782     else {
11783         scheduler = null;
11784     }
11785     var len = array.length;
11786     if (len === 1) {
11787         return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
11788     }
11789     else if (len > 1) {
11790         return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
11791     }
11792     else {
11793         return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
11794     }
11795 }
11796 exports.startWith = startWith;
11797
11798 },{"../observable/ArrayObservable":88,"../observable/EmptyObservable":91,"../observable/ScalarObservable":97,"../util/isScheduler":175,"./concat":115}],143:[function(require,module,exports){
11799 "use strict";
11800 var __extends = (this && this.__extends) || function (d, b) {
11801     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11802     function __() { this.constructor = d; }
11803     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11804 };
11805 var OuterSubscriber_1 = require('../OuterSubscriber');
11806 var subscribeToResult_1 = require('../util/subscribeToResult');
11807 /* tslint:enable:max-line-length */
11808 /**
11809  * Projects each source value to an Observable which is merged in the output
11810  * Observable, emitting values only from the most recently projected Observable.
11811  *
11812  * <span class="informal">Maps each value to an Observable, then flattens all of
11813  * these inner Observables using {@link switch}.</span>
11814  *
11815  * <img src="./img/switchMap.png" width="100%">
11816  *
11817  * Returns an Observable that emits items based on applying a function that you
11818  * supply to each item emitted by the source Observable, where that function
11819  * returns an (so-called "inner") Observable. Each time it observes one of these
11820  * inner Observables, the output Observable begins emitting the items emitted by
11821  * that inner Observable. When a new inner Observable is emitted, `switchMap`
11822  * stops emitting items from the earlier-emitted inner Observable and begins
11823  * emitting items from the new one. It continues to behave like this for
11824  * subsequent inner Observables.
11825  *
11826  * @example <caption>Rerun an interval Observable on every click event</caption>
11827  * var clicks = Rx.Observable.fromEvent(document, 'click');
11828  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
11829  * result.subscribe(x => console.log(x));
11830  *
11831  * @see {@link concatMap}
11832  * @see {@link exhaustMap}
11833  * @see {@link mergeMap}
11834  * @see {@link switch}
11835  * @see {@link switchMapTo}
11836  *
11837  * @param {function(value: T, ?index: number): ObservableInput} project A function
11838  * that, when applied to an item emitted by the source Observable, returns an
11839  * Observable.
11840  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
11841  * A function to produce the value on the output Observable based on the values
11842  * and the indices of the source (outer) emission and the inner Observable
11843  * emission. The arguments passed to this function are:
11844  * - `outerValue`: the value that came from the source
11845  * - `innerValue`: the value that came from the projected Observable
11846  * - `outerIndex`: the "index" of the value that came from the source
11847  * - `innerIndex`: the "index" of the value from the projected Observable
11848  * @return {Observable} An Observable that emits the result of applying the
11849  * projection function (and the optional `resultSelector`) to each item emitted
11850  * by the source Observable and taking only the values from the most recently
11851  * projected inner Observable.
11852  * @method switchMap
11853  * @owner Observable
11854  */
11855 function switchMap(project, resultSelector) {
11856     return this.lift(new SwitchMapOperator(project, resultSelector));
11857 }
11858 exports.switchMap = switchMap;
11859 var SwitchMapOperator = (function () {
11860     function SwitchMapOperator(project, resultSelector) {
11861         this.project = project;
11862         this.resultSelector = resultSelector;
11863     }
11864     SwitchMapOperator.prototype.call = function (subscriber, source) {
11865         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
11866     };
11867     return SwitchMapOperator;
11868 }());
11869 /**
11870  * We need this JSDoc comment for affecting ESDoc.
11871  * @ignore
11872  * @extends {Ignored}
11873  */
11874 var SwitchMapSubscriber = (function (_super) {
11875     __extends(SwitchMapSubscriber, _super);
11876     function SwitchMapSubscriber(destination, project, resultSelector) {
11877         _super.call(this, destination);
11878         this.project = project;
11879         this.resultSelector = resultSelector;
11880         this.index = 0;
11881     }
11882     SwitchMapSubscriber.prototype._next = function (value) {
11883         var result;
11884         var index = this.index++;
11885         try {
11886             result = this.project(value, index);
11887         }
11888         catch (error) {
11889             this.destination.error(error);
11890             return;
11891         }
11892         this._innerSub(result, value, index);
11893     };
11894     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
11895         var innerSubscription = this.innerSubscription;
11896         if (innerSubscription) {
11897             innerSubscription.unsubscribe();
11898         }
11899         this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
11900     };
11901     SwitchMapSubscriber.prototype._complete = function () {
11902         var innerSubscription = this.innerSubscription;
11903         if (!innerSubscription || innerSubscription.closed) {
11904             _super.prototype._complete.call(this);
11905         }
11906     };
11907     SwitchMapSubscriber.prototype._unsubscribe = function () {
11908         this.innerSubscription = null;
11909     };
11910     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
11911         this.remove(innerSub);
11912         this.innerSubscription = null;
11913         if (this.isStopped) {
11914             _super.prototype._complete.call(this);
11915         }
11916     };
11917     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11918         if (this.resultSelector) {
11919             this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
11920         }
11921         else {
11922             this.destination.next(innerValue);
11923         }
11924     };
11925     SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11926         var result;
11927         try {
11928             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11929         }
11930         catch (err) {
11931             this.destination.error(err);
11932             return;
11933         }
11934         this.destination.next(result);
11935     };
11936     return SwitchMapSubscriber;
11937 }(OuterSubscriber_1.OuterSubscriber));
11938
11939 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],144:[function(require,module,exports){
11940 "use strict";
11941 var __extends = (this && this.__extends) || function (d, b) {
11942     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11943     function __() { this.constructor = d; }
11944     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11945 };
11946 var Subscriber_1 = require('../Subscriber');
11947 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11948 var EmptyObservable_1 = require('../observable/EmptyObservable');
11949 /**
11950  * Emits only the first `count` values emitted by the source Observable.
11951  *
11952  * <span class="informal">Takes the first `count` values from the source, then
11953  * completes.</span>
11954  *
11955  * <img src="./img/take.png" width="100%">
11956  *
11957  * `take` returns an Observable that emits only the first `count` values emitted
11958  * by the source Observable. If the source emits fewer than `count` values then
11959  * all of its values are emitted. After that, it completes, regardless if the
11960  * source completes.
11961  *
11962  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11963  * var interval = Rx.Observable.interval(1000);
11964  * var five = interval.take(5);
11965  * five.subscribe(x => console.log(x));
11966  *
11967  * @see {@link takeLast}
11968  * @see {@link takeUntil}
11969  * @see {@link takeWhile}
11970  * @see {@link skip}
11971  *
11972  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11973  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11974  *
11975  * @param {number} count The maximum number of `next` values to emit.
11976  * @return {Observable<T>} An Observable that emits only the first `count`
11977  * values emitted by the source Observable, or all of the values from the source
11978  * if the source emits fewer than `count` values.
11979  * @method take
11980  * @owner Observable
11981  */
11982 function take(count) {
11983     if (count === 0) {
11984         return new EmptyObservable_1.EmptyObservable();
11985     }
11986     else {
11987         return this.lift(new TakeOperator(count));
11988     }
11989 }
11990 exports.take = take;
11991 var TakeOperator = (function () {
11992     function TakeOperator(total) {
11993         this.total = total;
11994         if (this.total < 0) {
11995             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11996         }
11997     }
11998     TakeOperator.prototype.call = function (subscriber, source) {
11999         return source.subscribe(new TakeSubscriber(subscriber, this.total));
12000     };
12001     return TakeOperator;
12002 }());
12003 /**
12004  * We need this JSDoc comment for affecting ESDoc.
12005  * @ignore
12006  * @extends {Ignored}
12007  */
12008 var TakeSubscriber = (function (_super) {
12009     __extends(TakeSubscriber, _super);
12010     function TakeSubscriber(destination, total) {
12011         _super.call(this, destination);
12012         this.total = total;
12013         this.count = 0;
12014     }
12015     TakeSubscriber.prototype._next = function (value) {
12016         var total = this.total;
12017         var count = ++this.count;
12018         if (count <= total) {
12019             this.destination.next(value);
12020             if (count === total) {
12021                 this.destination.complete();
12022                 this.unsubscribe();
12023             }
12024         }
12025     };
12026     return TakeSubscriber;
12027 }(Subscriber_1.Subscriber));
12028
12029 },{"../Subscriber":36,"../observable/EmptyObservable":91,"../util/ArgumentOutOfRangeError":162}],145:[function(require,module,exports){
12030 "use strict";
12031 var __extends = (this && this.__extends) || function (d, b) {
12032     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12033     function __() { this.constructor = d; }
12034     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12035 };
12036 var OuterSubscriber_1 = require('../OuterSubscriber');
12037 var subscribeToResult_1 = require('../util/subscribeToResult');
12038 /**
12039  * Emits the values emitted by the source Observable until a `notifier`
12040  * Observable emits a value.
12041  *
12042  * <span class="informal">Lets values pass until a second Observable,
12043  * `notifier`, emits something. Then, it completes.</span>
12044  *
12045  * <img src="./img/takeUntil.png" width="100%">
12046  *
12047  * `takeUntil` subscribes and begins mirroring the source Observable. It also
12048  * monitors a second Observable, `notifier` that you provide. If the `notifier`
12049  * emits a value or a complete notification, the output Observable stops
12050  * mirroring the source Observable and completes.
12051  *
12052  * @example <caption>Tick every second until the first click happens</caption>
12053  * var interval = Rx.Observable.interval(1000);
12054  * var clicks = Rx.Observable.fromEvent(document, 'click');
12055  * var result = interval.takeUntil(clicks);
12056  * result.subscribe(x => console.log(x));
12057  *
12058  * @see {@link take}
12059  * @see {@link takeLast}
12060  * @see {@link takeWhile}
12061  * @see {@link skip}
12062  *
12063  * @param {Observable} notifier The Observable whose first emitted value will
12064  * cause the output Observable of `takeUntil` to stop emitting values from the
12065  * source Observable.
12066  * @return {Observable<T>} An Observable that emits the values from the source
12067  * Observable until such time as `notifier` emits its first value.
12068  * @method takeUntil
12069  * @owner Observable
12070  */
12071 function takeUntil(notifier) {
12072     return this.lift(new TakeUntilOperator(notifier));
12073 }
12074 exports.takeUntil = takeUntil;
12075 var TakeUntilOperator = (function () {
12076     function TakeUntilOperator(notifier) {
12077         this.notifier = notifier;
12078     }
12079     TakeUntilOperator.prototype.call = function (subscriber, source) {
12080         return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
12081     };
12082     return TakeUntilOperator;
12083 }());
12084 /**
12085  * We need this JSDoc comment for affecting ESDoc.
12086  * @ignore
12087  * @extends {Ignored}
12088  */
12089 var TakeUntilSubscriber = (function (_super) {
12090     __extends(TakeUntilSubscriber, _super);
12091     function TakeUntilSubscriber(destination, notifier) {
12092         _super.call(this, destination);
12093         this.notifier = notifier;
12094         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
12095     }
12096     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12097         this.complete();
12098     };
12099     TakeUntilSubscriber.prototype.notifyComplete = function () {
12100         // noop
12101     };
12102     return TakeUntilSubscriber;
12103 }(OuterSubscriber_1.OuterSubscriber));
12104
12105 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],146:[function(require,module,exports){
12106 "use strict";
12107 var __extends = (this && this.__extends) || function (d, b) {
12108     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12109     function __() { this.constructor = d; }
12110     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12111 };
12112 var Subscriber_1 = require('../Subscriber');
12113 /**
12114  * Emits values emitted by the source Observable so long as each value satisfies
12115  * the given `predicate`, and then completes as soon as this `predicate` is not
12116  * satisfied.
12117  *
12118  * <span class="informal">Takes values from the source only while they pass the
12119  * condition given. When the first value does not satisfy, it completes.</span>
12120  *
12121  * <img src="./img/takeWhile.png" width="100%">
12122  *
12123  * `takeWhile` subscribes and begins mirroring the source Observable. Each value
12124  * emitted on the source is given to the `predicate` function which returns a
12125  * boolean, representing a condition to be satisfied by the source values. The
12126  * output Observable emits the source values until such time as the `predicate`
12127  * returns false, at which point `takeWhile` stops mirroring the source
12128  * Observable and completes the output Observable.
12129  *
12130  * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
12131  * var clicks = Rx.Observable.fromEvent(document, 'click');
12132  * var result = clicks.takeWhile(ev => ev.clientX > 200);
12133  * result.subscribe(x => console.log(x));
12134  *
12135  * @see {@link take}
12136  * @see {@link takeLast}
12137  * @see {@link takeUntil}
12138  * @see {@link skip}
12139  *
12140  * @param {function(value: T, index: number): boolean} predicate A function that
12141  * evaluates a value emitted by the source Observable and returns a boolean.
12142  * Also takes the (zero-based) index as the second argument.
12143  * @return {Observable<T>} An Observable that emits the values from the source
12144  * Observable so long as each value satisfies the condition defined by the
12145  * `predicate`, then completes.
12146  * @method takeWhile
12147  * @owner Observable
12148  */
12149 function takeWhile(predicate) {
12150     return this.lift(new TakeWhileOperator(predicate));
12151 }
12152 exports.takeWhile = takeWhile;
12153 var TakeWhileOperator = (function () {
12154     function TakeWhileOperator(predicate) {
12155         this.predicate = predicate;
12156     }
12157     TakeWhileOperator.prototype.call = function (subscriber, source) {
12158         return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
12159     };
12160     return TakeWhileOperator;
12161 }());
12162 /**
12163  * We need this JSDoc comment for affecting ESDoc.
12164  * @ignore
12165  * @extends {Ignored}
12166  */
12167 var TakeWhileSubscriber = (function (_super) {
12168     __extends(TakeWhileSubscriber, _super);
12169     function TakeWhileSubscriber(destination, predicate) {
12170         _super.call(this, destination);
12171         this.predicate = predicate;
12172         this.index = 0;
12173     }
12174     TakeWhileSubscriber.prototype._next = function (value) {
12175         var destination = this.destination;
12176         var result;
12177         try {
12178             result = this.predicate(value, this.index++);
12179         }
12180         catch (err) {
12181             destination.error(err);
12182             return;
12183         }
12184         this.nextOrComplete(value, result);
12185     };
12186     TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
12187         var destination = this.destination;
12188         if (Boolean(predicateResult)) {
12189             destination.next(value);
12190         }
12191         else {
12192             destination.complete();
12193         }
12194     };
12195     return TakeWhileSubscriber;
12196 }(Subscriber_1.Subscriber));
12197
12198 },{"../Subscriber":36}],147:[function(require,module,exports){
12199 "use strict";
12200 var __extends = (this && this.__extends) || function (d, b) {
12201     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12202     function __() { this.constructor = d; }
12203     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12204 };
12205 var OuterSubscriber_1 = require('../OuterSubscriber');
12206 var subscribeToResult_1 = require('../util/subscribeToResult');
12207 exports.defaultThrottleConfig = {
12208     leading: true,
12209     trailing: false
12210 };
12211 /**
12212  * Emits a value from the source Observable, then ignores subsequent source
12213  * values for a duration determined by another Observable, then repeats this
12214  * process.
12215  *
12216  * <span class="informal">It's like {@link throttleTime}, but the silencing
12217  * duration is determined by a second Observable.</span>
12218  *
12219  * <img src="./img/throttle.png" width="100%">
12220  *
12221  * `throttle` emits the source Observable values on the output Observable
12222  * when its internal timer is disabled, and ignores source values when the timer
12223  * is enabled. Initially, the timer is disabled. As soon as the first source
12224  * value arrives, it is forwarded to the output Observable, and then the timer
12225  * is enabled by calling the `durationSelector` function with the source value,
12226  * which returns the "duration" Observable. When the duration Observable emits a
12227  * value or completes, the timer is disabled, and this process repeats for the
12228  * next source value.
12229  *
12230  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12231  * var clicks = Rx.Observable.fromEvent(document, 'click');
12232  * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
12233  * result.subscribe(x => console.log(x));
12234  *
12235  * @see {@link audit}
12236  * @see {@link debounce}
12237  * @see {@link delayWhen}
12238  * @see {@link sample}
12239  * @see {@link throttleTime}
12240  *
12241  * @param {function(value: T): SubscribableOrPromise} durationSelector A function
12242  * that receives a value from the source Observable, for computing the silencing
12243  * duration for each source value, returned as an Observable or a Promise.
12244  * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
12245  * to `{ leading: true, trailing: false }`.
12246  * @return {Observable<T>} An Observable that performs the throttle operation to
12247  * limit the rate of emissions from the source.
12248  * @method throttle
12249  * @owner Observable
12250  */
12251 function throttle(durationSelector, config) {
12252     if (config === void 0) { config = exports.defaultThrottleConfig; }
12253     return this.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
12254 }
12255 exports.throttle = throttle;
12256 var ThrottleOperator = (function () {
12257     function ThrottleOperator(durationSelector, leading, trailing) {
12258         this.durationSelector = durationSelector;
12259         this.leading = leading;
12260         this.trailing = trailing;
12261     }
12262     ThrottleOperator.prototype.call = function (subscriber, source) {
12263         return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
12264     };
12265     return ThrottleOperator;
12266 }());
12267 /**
12268  * We need this JSDoc comment for affecting ESDoc
12269  * @ignore
12270  * @extends {Ignored}
12271  */
12272 var ThrottleSubscriber = (function (_super) {
12273     __extends(ThrottleSubscriber, _super);
12274     function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
12275         _super.call(this, destination);
12276         this.destination = destination;
12277         this.durationSelector = durationSelector;
12278         this._leading = _leading;
12279         this._trailing = _trailing;
12280         this._hasTrailingValue = false;
12281     }
12282     ThrottleSubscriber.prototype._next = function (value) {
12283         if (this.throttled) {
12284             if (this._trailing) {
12285                 this._hasTrailingValue = true;
12286                 this._trailingValue = value;
12287             }
12288         }
12289         else {
12290             var duration = this.tryDurationSelector(value);
12291             if (duration) {
12292                 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
12293             }
12294             if (this._leading) {
12295                 this.destination.next(value);
12296                 if (this._trailing) {
12297                     this._hasTrailingValue = true;
12298                     this._trailingValue = value;
12299                 }
12300             }
12301         }
12302     };
12303     ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
12304         try {
12305             return this.durationSelector(value);
12306         }
12307         catch (err) {
12308             this.destination.error(err);
12309             return null;
12310         }
12311     };
12312     ThrottleSubscriber.prototype._unsubscribe = function () {
12313         var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
12314         this._trailingValue = null;
12315         this._hasTrailingValue = false;
12316         if (throttled) {
12317             this.remove(throttled);
12318             this.throttled = null;
12319             throttled.unsubscribe();
12320         }
12321     };
12322     ThrottleSubscriber.prototype._sendTrailing = function () {
12323         var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
12324         if (throttled && _trailing && _hasTrailingValue) {
12325             destination.next(_trailingValue);
12326             this._trailingValue = null;
12327             this._hasTrailingValue = false;
12328         }
12329     };
12330     ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12331         this._sendTrailing();
12332         this._unsubscribe();
12333     };
12334     ThrottleSubscriber.prototype.notifyComplete = function () {
12335         this._sendTrailing();
12336         this._unsubscribe();
12337     };
12338     return ThrottleSubscriber;
12339 }(OuterSubscriber_1.OuterSubscriber));
12340
12341 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],148:[function(require,module,exports){
12342 "use strict";
12343 var __extends = (this && this.__extends) || function (d, b) {
12344     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12345     function __() { this.constructor = d; }
12346     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12347 };
12348 var Subscriber_1 = require('../Subscriber');
12349 var async_1 = require('../scheduler/async');
12350 var throttle_1 = require('./throttle');
12351 /**
12352  * Emits a value from the source Observable, then ignores subsequent source
12353  * values for `duration` milliseconds, then repeats this process.
12354  *
12355  * <span class="informal">Lets a value pass, then ignores source values for the
12356  * next `duration` milliseconds.</span>
12357  *
12358  * <img src="./img/throttleTime.png" width="100%">
12359  *
12360  * `throttleTime` emits the source Observable values on the output Observable
12361  * when its internal timer is disabled, and ignores source values when the timer
12362  * is enabled. Initially, the timer is disabled. As soon as the first source
12363  * value arrives, it is forwarded to the output Observable, and then the timer
12364  * is enabled. After `duration` milliseconds (or the time unit determined
12365  * internally by the optional `scheduler`) has passed, the timer is disabled,
12366  * and this process repeats for the next source value. Optionally takes a
12367  * {@link IScheduler} for managing timers.
12368  *
12369  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12370  * var clicks = Rx.Observable.fromEvent(document, 'click');
12371  * var result = clicks.throttleTime(1000);
12372  * result.subscribe(x => console.log(x));
12373  *
12374  * @see {@link auditTime}
12375  * @see {@link debounceTime}
12376  * @see {@link delay}
12377  * @see {@link sampleTime}
12378  * @see {@link throttle}
12379  *
12380  * @param {number} duration Time to wait before emitting another value after
12381  * emitting the last value, measured in milliseconds or the time unit determined
12382  * internally by the optional `scheduler`.
12383  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
12384  * managing the timers that handle the throttling.
12385  * @return {Observable<T>} An Observable that performs the throttle operation to
12386  * limit the rate of emissions from the source.
12387  * @method throttleTime
12388  * @owner Observable
12389  */
12390 function throttleTime(duration, scheduler, config) {
12391     if (scheduler === void 0) { scheduler = async_1.async; }
12392     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
12393     return this.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
12394 }
12395 exports.throttleTime = throttleTime;
12396 var ThrottleTimeOperator = (function () {
12397     function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
12398         this.duration = duration;
12399         this.scheduler = scheduler;
12400         this.leading = leading;
12401         this.trailing = trailing;
12402     }
12403     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
12404         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
12405     };
12406     return ThrottleTimeOperator;
12407 }());
12408 /**
12409  * We need this JSDoc comment for affecting ESDoc.
12410  * @ignore
12411  * @extends {Ignored}
12412  */
12413 var ThrottleTimeSubscriber = (function (_super) {
12414     __extends(ThrottleTimeSubscriber, _super);
12415     function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
12416         _super.call(this, destination);
12417         this.duration = duration;
12418         this.scheduler = scheduler;
12419         this.leading = leading;
12420         this.trailing = trailing;
12421         this._hasTrailingValue = false;
12422         this._trailingValue = null;
12423     }
12424     ThrottleTimeSubscriber.prototype._next = function (value) {
12425         if (this.throttled) {
12426             if (this.trailing) {
12427                 this._trailingValue = value;
12428                 this._hasTrailingValue = true;
12429             }
12430         }
12431         else {
12432             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
12433             if (this.leading) {
12434                 this.destination.next(value);
12435             }
12436         }
12437     };
12438     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
12439         var throttled = this.throttled;
12440         if (throttled) {
12441             if (this.trailing && this._hasTrailingValue) {
12442                 this.destination.next(this._trailingValue);
12443                 this._trailingValue = null;
12444                 this._hasTrailingValue = false;
12445             }
12446             throttled.unsubscribe();
12447             this.remove(throttled);
12448             this.throttled = null;
12449         }
12450     };
12451     return ThrottleTimeSubscriber;
12452 }(Subscriber_1.Subscriber));
12453 function dispatchNext(arg) {
12454     var subscriber = arg.subscriber;
12455     subscriber.clearThrottle();
12456 }
12457
12458 },{"../Subscriber":36,"../scheduler/async":156,"./throttle":147}],149:[function(require,module,exports){
12459 "use strict";
12460 var __extends = (this && this.__extends) || function (d, b) {
12461     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12462     function __() { this.constructor = d; }
12463     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12464 };
12465 var OuterSubscriber_1 = require('../OuterSubscriber');
12466 var subscribeToResult_1 = require('../util/subscribeToResult');
12467 /* tslint:enable:max-line-length */
12468 /**
12469  * Combines the source Observable with other Observables to create an Observable
12470  * whose values are calculated from the latest values of each, only when the
12471  * source emits.
12472  *
12473  * <span class="informal">Whenever the source Observable emits a value, it
12474  * computes a formula using that value plus the latest values from other input
12475  * Observables, then emits the output of that formula.</span>
12476  *
12477  * <img src="./img/withLatestFrom.png" width="100%">
12478  *
12479  * `withLatestFrom` combines each value from the source Observable (the
12480  * instance) with the latest values from the other input Observables only when
12481  * the source emits a value, optionally using a `project` function to determine
12482  * the value to be emitted on the output Observable. All input Observables must
12483  * emit at least one value before the output Observable will emit a value.
12484  *
12485  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
12486  * var clicks = Rx.Observable.fromEvent(document, 'click');
12487  * var timer = Rx.Observable.interval(1000);
12488  * var result = clicks.withLatestFrom(timer);
12489  * result.subscribe(x => console.log(x));
12490  *
12491  * @see {@link combineLatest}
12492  *
12493  * @param {ObservableInput} other An input Observable to combine with the source
12494  * Observable. More than one input Observables may be given as argument.
12495  * @param {Function} [project] Projection function for combining values
12496  * together. Receives all values in order of the Observables passed, where the
12497  * first parameter is a value from the source Observable. (e.g.
12498  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
12499  * passed, arrays will be emitted on the output Observable.
12500  * @return {Observable} An Observable of projected values from the most recent
12501  * values from each input Observable, or an array of the most recent values from
12502  * each input Observable.
12503  * @method withLatestFrom
12504  * @owner Observable
12505  */
12506 function withLatestFrom() {
12507     var args = [];
12508     for (var _i = 0; _i < arguments.length; _i++) {
12509         args[_i - 0] = arguments[_i];
12510     }
12511     var project;
12512     if (typeof args[args.length - 1] === 'function') {
12513         project = args.pop();
12514     }
12515     var observables = args;
12516     return this.lift(new WithLatestFromOperator(observables, project));
12517 }
12518 exports.withLatestFrom = withLatestFrom;
12519 var WithLatestFromOperator = (function () {
12520     function WithLatestFromOperator(observables, project) {
12521         this.observables = observables;
12522         this.project = project;
12523     }
12524     WithLatestFromOperator.prototype.call = function (subscriber, source) {
12525         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
12526     };
12527     return WithLatestFromOperator;
12528 }());
12529 /**
12530  * We need this JSDoc comment for affecting ESDoc.
12531  * @ignore
12532  * @extends {Ignored}
12533  */
12534 var WithLatestFromSubscriber = (function (_super) {
12535     __extends(WithLatestFromSubscriber, _super);
12536     function WithLatestFromSubscriber(destination, observables, project) {
12537         _super.call(this, destination);
12538         this.observables = observables;
12539         this.project = project;
12540         this.toRespond = [];
12541         var len = observables.length;
12542         this.values = new Array(len);
12543         for (var i = 0; i < len; i++) {
12544             this.toRespond.push(i);
12545         }
12546         for (var i = 0; i < len; i++) {
12547             var observable = observables[i];
12548             this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
12549         }
12550     }
12551     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12552         this.values[outerIndex] = innerValue;
12553         var toRespond = this.toRespond;
12554         if (toRespond.length > 0) {
12555             var found = toRespond.indexOf(outerIndex);
12556             if (found !== -1) {
12557                 toRespond.splice(found, 1);
12558             }
12559         }
12560     };
12561     WithLatestFromSubscriber.prototype.notifyComplete = function () {
12562         // noop
12563     };
12564     WithLatestFromSubscriber.prototype._next = function (value) {
12565         if (this.toRespond.length === 0) {
12566             var args = [value].concat(this.values);
12567             if (this.project) {
12568                 this._tryProject(args);
12569             }
12570             else {
12571                 this.destination.next(args);
12572             }
12573         }
12574     };
12575     WithLatestFromSubscriber.prototype._tryProject = function (args) {
12576         var result;
12577         try {
12578             result = this.project.apply(this, args);
12579         }
12580         catch (err) {
12581             this.destination.error(err);
12582             return;
12583         }
12584         this.destination.next(result);
12585     };
12586     return WithLatestFromSubscriber;
12587 }(OuterSubscriber_1.OuterSubscriber));
12588
12589 },{"../OuterSubscriber":31,"../util/subscribeToResult":177}],150:[function(require,module,exports){
12590 "use strict";
12591 var __extends = (this && this.__extends) || function (d, b) {
12592     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12593     function __() { this.constructor = d; }
12594     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12595 };
12596 var ArrayObservable_1 = require('../observable/ArrayObservable');
12597 var isArray_1 = require('../util/isArray');
12598 var Subscriber_1 = require('../Subscriber');
12599 var OuterSubscriber_1 = require('../OuterSubscriber');
12600 var subscribeToResult_1 = require('../util/subscribeToResult');
12601 var iterator_1 = require('../symbol/iterator');
12602 /* tslint:enable:max-line-length */
12603 /**
12604  * @param observables
12605  * @return {Observable<R>}
12606  * @method zip
12607  * @owner Observable
12608  */
12609 function zipProto() {
12610     var observables = [];
12611     for (var _i = 0; _i < arguments.length; _i++) {
12612         observables[_i - 0] = arguments[_i];
12613     }
12614     return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
12615 }
12616 exports.zipProto = zipProto;
12617 /* tslint:enable:max-line-length */
12618 /**
12619  * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
12620  * of its input Observables.
12621  *
12622  * If the latest parameter is a function, this function is used to compute the created value from the input values.
12623  * Otherwise, an array of the input values is returned.
12624  *
12625  * @example <caption>Combine age and name from different sources</caption>
12626  *
12627  * let age$ = Observable.of<number>(27, 25, 29);
12628  * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
12629  * let isDev$ = Observable.of<boolean>(true, true, false);
12630  *
12631  * Observable
12632  *     .zip(age$,
12633  *          name$,
12634  *          isDev$,
12635  *          (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
12636  *     .subscribe(x => console.log(x));
12637  *
12638  * // outputs
12639  * // { age: 27, name: 'Foo', isDev: true }
12640  * // { age: 25, name: 'Bar', isDev: true }
12641  * // { age: 29, name: 'Beer', isDev: false }
12642  *
12643  * @param observables
12644  * @return {Observable<R>}
12645  * @static true
12646  * @name zip
12647  * @owner Observable
12648  */
12649 function zipStatic() {
12650     var observables = [];
12651     for (var _i = 0; _i < arguments.length; _i++) {
12652         observables[_i - 0] = arguments[_i];
12653     }
12654     var project = observables[observables.length - 1];
12655     if (typeof project === 'function') {
12656         observables.pop();
12657     }
12658     return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
12659 }
12660 exports.zipStatic = zipStatic;
12661 var ZipOperator = (function () {
12662     function ZipOperator(project) {
12663         this.project = project;
12664     }
12665     ZipOperator.prototype.call = function (subscriber, source) {
12666         return source.subscribe(new ZipSubscriber(subscriber, this.project));
12667     };
12668     return ZipOperator;
12669 }());
12670 exports.ZipOperator = ZipOperator;
12671 /**
12672  * We need this JSDoc comment for affecting ESDoc.
12673  * @ignore
12674  * @extends {Ignored}
12675  */
12676 var ZipSubscriber = (function (_super) {
12677     __extends(ZipSubscriber, _super);
12678     function ZipSubscriber(destination, project, values) {
12679         if (values === void 0) { values = Object.create(null); }
12680         _super.call(this, destination);
12681         this.iterators = [];
12682         this.active = 0;
12683         this.project = (typeof project === 'function') ? project : null;
12684         this.values = values;
12685     }
12686     ZipSubscriber.prototype._next = function (value) {
12687         var iterators = this.iterators;
12688         if (isArray_1.isArray(value)) {
12689             iterators.push(new StaticArrayIterator(value));
12690         }
12691         else if (typeof value[iterator_1.iterator] === 'function') {
12692             iterators.push(new StaticIterator(value[iterator_1.iterator]()));
12693         }
12694         else {
12695             iterators.push(new ZipBufferIterator(this.destination, this, value));
12696         }
12697     };
12698     ZipSubscriber.prototype._complete = function () {
12699         var iterators = this.iterators;
12700         var len = iterators.length;
12701         if (len === 0) {
12702             this.destination.complete();
12703             return;
12704         }
12705         this.active = len;
12706         for (var i = 0; i < len; i++) {
12707             var iterator = iterators[i];
12708             if (iterator.stillUnsubscribed) {
12709                 this.add(iterator.subscribe(iterator, i));
12710             }
12711             else {
12712                 this.active--; // not an observable
12713             }
12714         }
12715     };
12716     ZipSubscriber.prototype.notifyInactive = function () {
12717         this.active--;
12718         if (this.active === 0) {
12719             this.destination.complete();
12720         }
12721     };
12722     ZipSubscriber.prototype.checkIterators = function () {
12723         var iterators = this.iterators;
12724         var len = iterators.length;
12725         var destination = this.destination;
12726         // abort if not all of them have values
12727         for (var i = 0; i < len; i++) {
12728             var iterator = iterators[i];
12729             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
12730                 return;
12731             }
12732         }
12733         var shouldComplete = false;
12734         var args = [];
12735         for (var i = 0; i < len; i++) {
12736             var iterator = iterators[i];
12737             var result = iterator.next();
12738             // check to see if it's completed now that you've gotten
12739             // the next value.
12740             if (iterator.hasCompleted()) {
12741                 shouldComplete = true;
12742             }
12743             if (result.done) {
12744                 destination.complete();
12745                 return;
12746             }
12747             args.push(result.value);
12748         }
12749         if (this.project) {
12750             this._tryProject(args);
12751         }
12752         else {
12753             destination.next(args);
12754         }
12755         if (shouldComplete) {
12756             destination.complete();
12757         }
12758     };
12759     ZipSubscriber.prototype._tryProject = function (args) {
12760         var result;
12761         try {
12762             result = this.project.apply(this, args);
12763         }
12764         catch (err) {
12765             this.destination.error(err);
12766             return;
12767         }
12768         this.destination.next(result);
12769     };
12770     return ZipSubscriber;
12771 }(Subscriber_1.Subscriber));
12772 exports.ZipSubscriber = ZipSubscriber;
12773 var StaticIterator = (function () {
12774     function StaticIterator(iterator) {
12775         this.iterator = iterator;
12776         this.nextResult = iterator.next();
12777     }
12778     StaticIterator.prototype.hasValue = function () {
12779         return true;
12780     };
12781     StaticIterator.prototype.next = function () {
12782         var result = this.nextResult;
12783         this.nextResult = this.iterator.next();
12784         return result;
12785     };
12786     StaticIterator.prototype.hasCompleted = function () {
12787         var nextResult = this.nextResult;
12788         return nextResult && nextResult.done;
12789     };
12790     return StaticIterator;
12791 }());
12792 var StaticArrayIterator = (function () {
12793     function StaticArrayIterator(array) {
12794         this.array = array;
12795         this.index = 0;
12796         this.length = 0;
12797         this.length = array.length;
12798     }
12799     StaticArrayIterator.prototype[iterator_1.iterator] = function () {
12800         return this;
12801     };
12802     StaticArrayIterator.prototype.next = function (value) {
12803         var i = this.index++;
12804         var array = this.array;
12805         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
12806     };
12807     StaticArrayIterator.prototype.hasValue = function () {
12808         return this.array.length > this.index;
12809     };
12810     StaticArrayIterator.prototype.hasCompleted = function () {
12811         return this.array.length === this.index;
12812     };
12813     return StaticArrayIterator;
12814 }());
12815 /**
12816  * We need this JSDoc comment for affecting ESDoc.
12817  * @ignore
12818  * @extends {Ignored}
12819  */
12820 var ZipBufferIterator = (function (_super) {
12821     __extends(ZipBufferIterator, _super);
12822     function ZipBufferIterator(destination, parent, observable) {
12823         _super.call(this, destination);
12824         this.parent = parent;
12825         this.observable = observable;
12826         this.stillUnsubscribed = true;
12827         this.buffer = [];
12828         this.isComplete = false;
12829     }
12830     ZipBufferIterator.prototype[iterator_1.iterator] = function () {
12831         return this;
12832     };
12833     // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
12834     //    this is legit because `next()` will never be called by a subscription in this case.
12835     ZipBufferIterator.prototype.next = function () {
12836         var buffer = this.buffer;
12837         if (buffer.length === 0 && this.isComplete) {
12838             return { value: null, done: true };
12839         }
12840         else {
12841             return { value: buffer.shift(), done: false };
12842         }
12843     };
12844     ZipBufferIterator.prototype.hasValue = function () {
12845         return this.buffer.length > 0;
12846     };
12847     ZipBufferIterator.prototype.hasCompleted = function () {
12848         return this.buffer.length === 0 && this.isComplete;
12849     };
12850     ZipBufferIterator.prototype.notifyComplete = function () {
12851         if (this.buffer.length > 0) {
12852             this.isComplete = true;
12853             this.parent.notifyInactive();
12854         }
12855         else {
12856             this.destination.complete();
12857         }
12858     };
12859     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12860         this.buffer.push(innerValue);
12861         this.parent.checkIterators();
12862     };
12863     ZipBufferIterator.prototype.subscribe = function (value, index) {
12864         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
12865     };
12866     return ZipBufferIterator;
12867 }(OuterSubscriber_1.OuterSubscriber));
12868
12869 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":88,"../symbol/iterator":158,"../util/isArray":168,"../util/subscribeToResult":177}],151:[function(require,module,exports){
12870 "use strict";
12871 var __extends = (this && this.__extends) || function (d, b) {
12872     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12873     function __() { this.constructor = d; }
12874     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12875 };
12876 var Subscription_1 = require('../Subscription');
12877 /**
12878  * A unit of work to be executed in a {@link Scheduler}. An action is typically
12879  * created from within a Scheduler and an RxJS user does not need to concern
12880  * themselves about creating and manipulating an Action.
12881  *
12882  * ```ts
12883  * class Action<T> extends Subscription {
12884  *   new (scheduler: Scheduler, work: (state?: T) => void);
12885  *   schedule(state?: T, delay: number = 0): Subscription;
12886  * }
12887  * ```
12888  *
12889  * @class Action<T>
12890  */
12891 var Action = (function (_super) {
12892     __extends(Action, _super);
12893     function Action(scheduler, work) {
12894         _super.call(this);
12895     }
12896     /**
12897      * Schedules this action on its parent Scheduler for execution. May be passed
12898      * some context object, `state`. May happen at some point in the future,
12899      * according to the `delay` parameter, if specified.
12900      * @param {T} [state] Some contextual data that the `work` function uses when
12901      * called by the Scheduler.
12902      * @param {number} [delay] Time to wait before executing the work, where the
12903      * time unit is implicit and defined by the Scheduler.
12904      * @return {void}
12905      */
12906     Action.prototype.schedule = function (state, delay) {
12907         if (delay === void 0) { delay = 0; }
12908         return this;
12909     };
12910     return Action;
12911 }(Subscription_1.Subscription));
12912 exports.Action = Action;
12913
12914 },{"../Subscription":37}],152:[function(require,module,exports){
12915 "use strict";
12916 var __extends = (this && this.__extends) || function (d, b) {
12917     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12918     function __() { this.constructor = d; }
12919     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12920 };
12921 var root_1 = require('../util/root');
12922 var Action_1 = require('./Action');
12923 /**
12924  * We need this JSDoc comment for affecting ESDoc.
12925  * @ignore
12926  * @extends {Ignored}
12927  */
12928 var AsyncAction = (function (_super) {
12929     __extends(AsyncAction, _super);
12930     function AsyncAction(scheduler, work) {
12931         _super.call(this, scheduler, work);
12932         this.scheduler = scheduler;
12933         this.work = work;
12934         this.pending = false;
12935     }
12936     AsyncAction.prototype.schedule = function (state, delay) {
12937         if (delay === void 0) { delay = 0; }
12938         if (this.closed) {
12939             return this;
12940         }
12941         // Always replace the current state with the new state.
12942         this.state = state;
12943         // Set the pending flag indicating that this action has been scheduled, or
12944         // has recursively rescheduled itself.
12945         this.pending = true;
12946         var id = this.id;
12947         var scheduler = this.scheduler;
12948         //
12949         // Important implementation note:
12950         //
12951         // Actions only execute once by default, unless rescheduled from within the
12952         // scheduled callback. This allows us to implement single and repeat
12953         // actions via the same code path, without adding API surface area, as well
12954         // as mimic traditional recursion but across asynchronous boundaries.
12955         //
12956         // However, JS runtimes and timers distinguish between intervals achieved by
12957         // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
12958         // serial `setTimeout` calls can be individually delayed, which delays
12959         // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
12960         // guarantee the interval callback will be invoked more precisely to the
12961         // interval period, regardless of load.
12962         //
12963         // Therefore, we use `setInterval` to schedule single and repeat actions.
12964         // If the action reschedules itself with the same delay, the interval is not
12965         // canceled. If the action doesn't reschedule, or reschedules with a
12966         // different delay, the interval will be canceled after scheduled callback
12967         // execution.
12968         //
12969         if (id != null) {
12970             this.id = this.recycleAsyncId(scheduler, id, delay);
12971         }
12972         this.delay = delay;
12973         // If this action has already an async Id, don't request a new one.
12974         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
12975         return this;
12976     };
12977     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12978         if (delay === void 0) { delay = 0; }
12979         return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
12980     };
12981     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
12982         if (delay === void 0) { delay = 0; }
12983         // If this action is rescheduled with the same delay time, don't clear the interval id.
12984         if (delay !== null && this.delay === delay && this.pending === false) {
12985             return id;
12986         }
12987         // Otherwise, if the action's delay time is different from the current delay,
12988         // or the action has been rescheduled before it's executed, clear the interval id
12989         return root_1.root.clearInterval(id) && undefined || undefined;
12990     };
12991     /**
12992      * Immediately executes this action and the `work` it contains.
12993      * @return {any}
12994      */
12995     AsyncAction.prototype.execute = function (state, delay) {
12996         if (this.closed) {
12997             return new Error('executing a cancelled action');
12998         }
12999         this.pending = false;
13000         var error = this._execute(state, delay);
13001         if (error) {
13002             return error;
13003         }
13004         else if (this.pending === false && this.id != null) {
13005             // Dequeue if the action didn't reschedule itself. Don't call
13006             // unsubscribe(), because the action could reschedule later.
13007             // For example:
13008             // ```
13009             // scheduler.schedule(function doWork(counter) {
13010             //   /* ... I'm a busy worker bee ... */
13011             //   var originalAction = this;
13012             //   /* wait 100ms before rescheduling the action */
13013             //   setTimeout(function () {
13014             //     originalAction.schedule(counter + 1);
13015             //   }, 100);
13016             // }, 1000);
13017             // ```
13018             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
13019         }
13020     };
13021     AsyncAction.prototype._execute = function (state, delay) {
13022         var errored = false;
13023         var errorValue = undefined;
13024         try {
13025             this.work(state);
13026         }
13027         catch (e) {
13028             errored = true;
13029             errorValue = !!e && e || new Error(e);
13030         }
13031         if (errored) {
13032             this.unsubscribe();
13033             return errorValue;
13034         }
13035     };
13036     AsyncAction.prototype._unsubscribe = function () {
13037         var id = this.id;
13038         var scheduler = this.scheduler;
13039         var actions = scheduler.actions;
13040         var index = actions.indexOf(this);
13041         this.work = null;
13042         this.state = null;
13043         this.pending = false;
13044         this.scheduler = null;
13045         if (index !== -1) {
13046             actions.splice(index, 1);
13047         }
13048         if (id != null) {
13049             this.id = this.recycleAsyncId(scheduler, id, null);
13050         }
13051         this.delay = null;
13052     };
13053     return AsyncAction;
13054 }(Action_1.Action));
13055 exports.AsyncAction = AsyncAction;
13056
13057 },{"../util/root":176,"./Action":151}],153:[function(require,module,exports){
13058 "use strict";
13059 var __extends = (this && this.__extends) || function (d, b) {
13060     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13061     function __() { this.constructor = d; }
13062     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13063 };
13064 var Scheduler_1 = require('../Scheduler');
13065 var AsyncScheduler = (function (_super) {
13066     __extends(AsyncScheduler, _super);
13067     function AsyncScheduler() {
13068         _super.apply(this, arguments);
13069         this.actions = [];
13070         /**
13071          * A flag to indicate whether the Scheduler is currently executing a batch of
13072          * queued actions.
13073          * @type {boolean}
13074          */
13075         this.active = false;
13076         /**
13077          * An internal ID used to track the latest asynchronous task such as those
13078          * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
13079          * others.
13080          * @type {any}
13081          */
13082         this.scheduled = undefined;
13083     }
13084     AsyncScheduler.prototype.flush = function (action) {
13085         var actions = this.actions;
13086         if (this.active) {
13087             actions.push(action);
13088             return;
13089         }
13090         var error;
13091         this.active = true;
13092         do {
13093             if (error = action.execute(action.state, action.delay)) {
13094                 break;
13095             }
13096         } while (action = actions.shift()); // exhaust the scheduler queue
13097         this.active = false;
13098         if (error) {
13099             while (action = actions.shift()) {
13100                 action.unsubscribe();
13101             }
13102             throw error;
13103         }
13104     };
13105     return AsyncScheduler;
13106 }(Scheduler_1.Scheduler));
13107 exports.AsyncScheduler = AsyncScheduler;
13108
13109 },{"../Scheduler":33}],154:[function(require,module,exports){
13110 "use strict";
13111 var __extends = (this && this.__extends) || function (d, b) {
13112     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13113     function __() { this.constructor = d; }
13114     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13115 };
13116 var AsyncAction_1 = require('./AsyncAction');
13117 /**
13118  * We need this JSDoc comment for affecting ESDoc.
13119  * @ignore
13120  * @extends {Ignored}
13121  */
13122 var QueueAction = (function (_super) {
13123     __extends(QueueAction, _super);
13124     function QueueAction(scheduler, work) {
13125         _super.call(this, scheduler, work);
13126         this.scheduler = scheduler;
13127         this.work = work;
13128     }
13129     QueueAction.prototype.schedule = function (state, delay) {
13130         if (delay === void 0) { delay = 0; }
13131         if (delay > 0) {
13132             return _super.prototype.schedule.call(this, state, delay);
13133         }
13134         this.delay = delay;
13135         this.state = state;
13136         this.scheduler.flush(this);
13137         return this;
13138     };
13139     QueueAction.prototype.execute = function (state, delay) {
13140         return (delay > 0 || this.closed) ?
13141             _super.prototype.execute.call(this, state, delay) :
13142             this._execute(state, delay);
13143     };
13144     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
13145         if (delay === void 0) { delay = 0; }
13146         // If delay exists and is greater than 0, or if the delay is null (the
13147         // action wasn't rescheduled) but was originally scheduled as an async
13148         // action, then recycle as an async action.
13149         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
13150             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
13151         }
13152         // Otherwise flush the scheduler starting with this action.
13153         return scheduler.flush(this);
13154     };
13155     return QueueAction;
13156 }(AsyncAction_1.AsyncAction));
13157 exports.QueueAction = QueueAction;
13158
13159 },{"./AsyncAction":152}],155:[function(require,module,exports){
13160 "use strict";
13161 var __extends = (this && this.__extends) || function (d, b) {
13162     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13163     function __() { this.constructor = d; }
13164     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13165 };
13166 var AsyncScheduler_1 = require('./AsyncScheduler');
13167 var QueueScheduler = (function (_super) {
13168     __extends(QueueScheduler, _super);
13169     function QueueScheduler() {
13170         _super.apply(this, arguments);
13171     }
13172     return QueueScheduler;
13173 }(AsyncScheduler_1.AsyncScheduler));
13174 exports.QueueScheduler = QueueScheduler;
13175
13176 },{"./AsyncScheduler":153}],156:[function(require,module,exports){
13177 "use strict";
13178 var AsyncAction_1 = require('./AsyncAction');
13179 var AsyncScheduler_1 = require('./AsyncScheduler');
13180 /**
13181  *
13182  * Async Scheduler
13183  *
13184  * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
13185  *
13186  * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
13187  * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
13188  * in intervals.
13189  *
13190  * If you just want to "defer" task, that is to perform it right after currently
13191  * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
13192  * better choice will be the {@link asap} scheduler.
13193  *
13194  * @example <caption>Use async scheduler to delay task</caption>
13195  * const task = () => console.log('it works!');
13196  *
13197  * Rx.Scheduler.async.schedule(task, 2000);
13198  *
13199  * // After 2 seconds logs:
13200  * // "it works!"
13201  *
13202  *
13203  * @example <caption>Use async scheduler to repeat task in intervals</caption>
13204  * function task(state) {
13205  *   console.log(state);
13206  *   this.schedule(state + 1, 1000); // `this` references currently executing Action,
13207  *                                   // which we reschedule with new state and delay
13208  * }
13209  *
13210  * Rx.Scheduler.async.schedule(task, 3000, 0);
13211  *
13212  * // Logs:
13213  * // 0 after 3s
13214  * // 1 after 4s
13215  * // 2 after 5s
13216  * // 3 after 6s
13217  *
13218  * @static true
13219  * @name async
13220  * @owner Scheduler
13221  */
13222 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
13223
13224 },{"./AsyncAction":152,"./AsyncScheduler":153}],157:[function(require,module,exports){
13225 "use strict";
13226 var QueueAction_1 = require('./QueueAction');
13227 var QueueScheduler_1 = require('./QueueScheduler');
13228 /**
13229  *
13230  * Queue Scheduler
13231  *
13232  * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
13233  *
13234  * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
13235  *
13236  * When used without delay, it schedules given task synchronously - executes it right when
13237  * it is scheduled. However when called recursively, that is when inside the scheduled task,
13238  * another task is scheduled with queue scheduler, instead of executing immediately as well,
13239  * that task will be put on a queue and wait for current one to finish.
13240  *
13241  * This means that when you execute task with `queue` scheduler, you are sure it will end
13242  * before any other task scheduled with that scheduler will start.
13243  *
13244  * @examples <caption>Schedule recursively first, then do something</caption>
13245  *
13246  * Rx.Scheduler.queue.schedule(() => {
13247  *   Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
13248  *
13249  *   console.log('first');
13250  * });
13251  *
13252  * // Logs:
13253  * // "first"
13254  * // "second"
13255  *
13256  *
13257  * @example <caption>Reschedule itself recursively</caption>
13258  *
13259  * Rx.Scheduler.queue.schedule(function(state) {
13260  *   if (state !== 0) {
13261  *     console.log('before', state);
13262  *     this.schedule(state - 1); // `this` references currently executing Action,
13263  *                               // which we reschedule with new state
13264  *     console.log('after', state);
13265  *   }
13266  * }, 0, 3);
13267  *
13268  * // In scheduler that runs recursively, you would expect:
13269  * // "before", 3
13270  * // "before", 2
13271  * // "before", 1
13272  * // "after", 1
13273  * // "after", 2
13274  * // "after", 3
13275  *
13276  * // But with queue it logs:
13277  * // "before", 3
13278  * // "after", 3
13279  * // "before", 2
13280  * // "after", 2
13281  * // "before", 1
13282  * // "after", 1
13283  *
13284  *
13285  * @static true
13286  * @name queue
13287  * @owner Scheduler
13288  */
13289 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
13290
13291 },{"./QueueAction":154,"./QueueScheduler":155}],158:[function(require,module,exports){
13292 "use strict";
13293 var root_1 = require('../util/root');
13294 function symbolIteratorPonyfill(root) {
13295     var Symbol = root.Symbol;
13296     if (typeof Symbol === 'function') {
13297         if (!Symbol.iterator) {
13298             Symbol.iterator = Symbol('iterator polyfill');
13299         }
13300         return Symbol.iterator;
13301     }
13302     else {
13303         // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
13304         var Set_1 = root.Set;
13305         if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
13306             return '@@iterator';
13307         }
13308         var Map_1 = root.Map;
13309         // required for compatability with es6-shim
13310         if (Map_1) {
13311             var keys = Object.getOwnPropertyNames(Map_1.prototype);
13312             for (var i = 0; i < keys.length; ++i) {
13313                 var key = keys[i];
13314                 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
13315                 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
13316                     return key;
13317                 }
13318             }
13319         }
13320         return '@@iterator';
13321     }
13322 }
13323 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
13324 exports.iterator = symbolIteratorPonyfill(root_1.root);
13325 /**
13326  * @deprecated use iterator instead
13327  */
13328 exports.$$iterator = exports.iterator;
13329
13330 },{"../util/root":176}],159:[function(require,module,exports){
13331 "use strict";
13332 var root_1 = require('../util/root');
13333 function getSymbolObservable(context) {
13334     var $$observable;
13335     var Symbol = context.Symbol;
13336     if (typeof Symbol === 'function') {
13337         if (Symbol.observable) {
13338             $$observable = Symbol.observable;
13339         }
13340         else {
13341             $$observable = Symbol('observable');
13342             Symbol.observable = $$observable;
13343         }
13344     }
13345     else {
13346         $$observable = '@@observable';
13347     }
13348     return $$observable;
13349 }
13350 exports.getSymbolObservable = getSymbolObservable;
13351 exports.observable = getSymbolObservable(root_1.root);
13352 /**
13353  * @deprecated use observable instead
13354  */
13355 exports.$$observable = exports.observable;
13356
13357 },{"../util/root":176}],160:[function(require,module,exports){
13358 "use strict";
13359 var root_1 = require('../util/root');
13360 var Symbol = root_1.root.Symbol;
13361 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
13362     Symbol.for('rxSubscriber') : '@@rxSubscriber';
13363 /**
13364  * @deprecated use rxSubscriber instead
13365  */
13366 exports.$$rxSubscriber = exports.rxSubscriber;
13367
13368 },{"../util/root":176}],161:[function(require,module,exports){
13369 "use strict";
13370 var root_1 = require('./root');
13371 var RequestAnimationFrameDefinition = (function () {
13372     function RequestAnimationFrameDefinition(root) {
13373         if (root.requestAnimationFrame) {
13374             this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
13375             this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
13376         }
13377         else if (root.mozRequestAnimationFrame) {
13378             this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
13379             this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
13380         }
13381         else if (root.webkitRequestAnimationFrame) {
13382             this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
13383             this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
13384         }
13385         else if (root.msRequestAnimationFrame) {
13386             this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
13387             this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
13388         }
13389         else if (root.oRequestAnimationFrame) {
13390             this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
13391             this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
13392         }
13393         else {
13394             this.cancelAnimationFrame = root.clearTimeout.bind(root);
13395             this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
13396         }
13397     }
13398     return RequestAnimationFrameDefinition;
13399 }());
13400 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
13401 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
13402
13403 },{"./root":176}],162:[function(require,module,exports){
13404 "use strict";
13405 var __extends = (this && this.__extends) || function (d, b) {
13406     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13407     function __() { this.constructor = d; }
13408     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13409 };
13410 /**
13411  * An error thrown when an element was queried at a certain index of an
13412  * Observable, but no such index or position exists in that sequence.
13413  *
13414  * @see {@link elementAt}
13415  * @see {@link take}
13416  * @see {@link takeLast}
13417  *
13418  * @class ArgumentOutOfRangeError
13419  */
13420 var ArgumentOutOfRangeError = (function (_super) {
13421     __extends(ArgumentOutOfRangeError, _super);
13422     function ArgumentOutOfRangeError() {
13423         var err = _super.call(this, 'argument out of range');
13424         this.name = err.name = 'ArgumentOutOfRangeError';
13425         this.stack = err.stack;
13426         this.message = err.message;
13427     }
13428     return ArgumentOutOfRangeError;
13429 }(Error));
13430 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
13431
13432 },{}],163:[function(require,module,exports){
13433 "use strict";
13434 var __extends = (this && this.__extends) || function (d, b) {
13435     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13436     function __() { this.constructor = d; }
13437     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13438 };
13439 /**
13440  * An error thrown when an Observable or a sequence was queried but has no
13441  * elements.
13442  *
13443  * @see {@link first}
13444  * @see {@link last}
13445  * @see {@link single}
13446  *
13447  * @class EmptyError
13448  */
13449 var EmptyError = (function (_super) {
13450     __extends(EmptyError, _super);
13451     function EmptyError() {
13452         var err = _super.call(this, 'no elements in sequence');
13453         this.name = err.name = 'EmptyError';
13454         this.stack = err.stack;
13455         this.message = err.message;
13456     }
13457     return EmptyError;
13458 }(Error));
13459 exports.EmptyError = EmptyError;
13460
13461 },{}],164:[function(require,module,exports){
13462 "use strict";
13463 var __extends = (this && this.__extends) || function (d, b) {
13464     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13465     function __() { this.constructor = d; }
13466     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13467 };
13468 /**
13469  * An error thrown when an action is invalid because the object has been
13470  * unsubscribed.
13471  *
13472  * @see {@link Subject}
13473  * @see {@link BehaviorSubject}
13474  *
13475  * @class ObjectUnsubscribedError
13476  */
13477 var ObjectUnsubscribedError = (function (_super) {
13478     __extends(ObjectUnsubscribedError, _super);
13479     function ObjectUnsubscribedError() {
13480         var err = _super.call(this, 'object unsubscribed');
13481         this.name = err.name = 'ObjectUnsubscribedError';
13482         this.stack = err.stack;
13483         this.message = err.message;
13484     }
13485     return ObjectUnsubscribedError;
13486 }(Error));
13487 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
13488
13489 },{}],165:[function(require,module,exports){
13490 "use strict";
13491 var root_1 = require('./root');
13492 function minimalSetImpl() {
13493     // THIS IS NOT a full impl of Set, this is just the minimum
13494     // bits of functionality we need for this library.
13495     return (function () {
13496         function MinimalSet() {
13497             this._values = [];
13498         }
13499         MinimalSet.prototype.add = function (value) {
13500             if (!this.has(value)) {
13501                 this._values.push(value);
13502             }
13503         };
13504         MinimalSet.prototype.has = function (value) {
13505             return this._values.indexOf(value) !== -1;
13506         };
13507         Object.defineProperty(MinimalSet.prototype, "size", {
13508             get: function () {
13509                 return this._values.length;
13510             },
13511             enumerable: true,
13512             configurable: true
13513         });
13514         MinimalSet.prototype.clear = function () {
13515             this._values.length = 0;
13516         };
13517         return MinimalSet;
13518     }());
13519 }
13520 exports.minimalSetImpl = minimalSetImpl;
13521 exports.Set = root_1.root.Set || minimalSetImpl();
13522
13523 },{"./root":176}],166:[function(require,module,exports){
13524 "use strict";
13525 var __extends = (this && this.__extends) || function (d, b) {
13526     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13527     function __() { this.constructor = d; }
13528     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13529 };
13530 /**
13531  * An error thrown when one or more errors have occurred during the
13532  * `unsubscribe` of a {@link Subscription}.
13533  */
13534 var UnsubscriptionError = (function (_super) {
13535     __extends(UnsubscriptionError, _super);
13536     function UnsubscriptionError(errors) {
13537         _super.call(this);
13538         this.errors = errors;
13539         var err = Error.call(this, errors ?
13540             errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
13541         this.name = err.name = 'UnsubscriptionError';
13542         this.stack = err.stack;
13543         this.message = err.message;
13544     }
13545     return UnsubscriptionError;
13546 }(Error));
13547 exports.UnsubscriptionError = UnsubscriptionError;
13548
13549 },{}],167:[function(require,module,exports){
13550 "use strict";
13551 // typeof any so that it we don't have to cast when comparing a result to the error object
13552 exports.errorObject = { e: {} };
13553
13554 },{}],168:[function(require,module,exports){
13555 "use strict";
13556 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
13557
13558 },{}],169:[function(require,module,exports){
13559 "use strict";
13560 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
13561
13562 },{}],170:[function(require,module,exports){
13563 "use strict";
13564 function isDate(value) {
13565     return value instanceof Date && !isNaN(+value);
13566 }
13567 exports.isDate = isDate;
13568
13569 },{}],171:[function(require,module,exports){
13570 "use strict";
13571 function isFunction(x) {
13572     return typeof x === 'function';
13573 }
13574 exports.isFunction = isFunction;
13575
13576 },{}],172:[function(require,module,exports){
13577 "use strict";
13578 var isArray_1 = require('../util/isArray');
13579 function isNumeric(val) {
13580     // parseFloat NaNs numeric-cast false positives (null|true|false|"")
13581     // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
13582     // subtraction forces infinities to NaN
13583     // adding 1 corrects loss of precision from parseFloat (#15100)
13584     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
13585 }
13586 exports.isNumeric = isNumeric;
13587 ;
13588
13589 },{"../util/isArray":168}],173:[function(require,module,exports){
13590 "use strict";
13591 function isObject(x) {
13592     return x != null && typeof x === 'object';
13593 }
13594 exports.isObject = isObject;
13595
13596 },{}],174:[function(require,module,exports){
13597 "use strict";
13598 function isPromise(value) {
13599     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
13600 }
13601 exports.isPromise = isPromise;
13602
13603 },{}],175:[function(require,module,exports){
13604 "use strict";
13605 function isScheduler(value) {
13606     return value && typeof value.schedule === 'function';
13607 }
13608 exports.isScheduler = isScheduler;
13609
13610 },{}],176:[function(require,module,exports){
13611 (function (global){
13612 "use strict";
13613 // CommonJS / Node have global context exposed as "global" variable.
13614 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
13615 // the global "global" var for now.
13616 var __window = typeof window !== 'undefined' && window;
13617 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
13618     self instanceof WorkerGlobalScope && self;
13619 var __global = typeof global !== 'undefined' && global;
13620 var _root = __window || __global || __self;
13621 exports.root = _root;
13622 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
13623 // This is needed when used with angular/tsickle which inserts a goog.module statement.
13624 // Wrap in IIFE
13625 (function () {
13626     if (!_root) {
13627         throw new Error('RxJS could not find any global context (window, self, global)');
13628     }
13629 })();
13630
13631 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13632
13633 },{}],177:[function(require,module,exports){
13634 "use strict";
13635 var root_1 = require('./root');
13636 var isArrayLike_1 = require('./isArrayLike');
13637 var isPromise_1 = require('./isPromise');
13638 var isObject_1 = require('./isObject');
13639 var Observable_1 = require('../Observable');
13640 var iterator_1 = require('../symbol/iterator');
13641 var InnerSubscriber_1 = require('../InnerSubscriber');
13642 var observable_1 = require('../symbol/observable');
13643 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
13644     var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
13645     if (destination.closed) {
13646         return null;
13647     }
13648     if (result instanceof Observable_1.Observable) {
13649         if (result._isScalar) {
13650             destination.next(result.value);
13651             destination.complete();
13652             return null;
13653         }
13654         else {
13655             return result.subscribe(destination);
13656         }
13657     }
13658     else if (isArrayLike_1.isArrayLike(result)) {
13659         for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
13660             destination.next(result[i]);
13661         }
13662         if (!destination.closed) {
13663             destination.complete();
13664         }
13665     }
13666     else if (isPromise_1.isPromise(result)) {
13667         result.then(function (value) {
13668             if (!destination.closed) {
13669                 destination.next(value);
13670                 destination.complete();
13671             }
13672         }, function (err) { return destination.error(err); })
13673             .then(null, function (err) {
13674             // Escaping the Promise trap: globally throw unhandled errors
13675             root_1.root.setTimeout(function () { throw err; });
13676         });
13677         return destination;
13678     }
13679     else if (result && typeof result[iterator_1.iterator] === 'function') {
13680         var iterator = result[iterator_1.iterator]();
13681         do {
13682             var item = iterator.next();
13683             if (item.done) {
13684                 destination.complete();
13685                 break;
13686             }
13687             destination.next(item.value);
13688             if (destination.closed) {
13689                 break;
13690             }
13691         } while (true);
13692     }
13693     else if (result && typeof result[observable_1.observable] === 'function') {
13694         var obs = result[observable_1.observable]();
13695         if (typeof obs.subscribe !== 'function') {
13696             destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
13697         }
13698         else {
13699             return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
13700         }
13701     }
13702     else {
13703         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
13704         var msg = ("You provided " + value + " where a stream was expected.")
13705             + ' You can provide an Observable, Promise, Array, or Iterable.';
13706         destination.error(new TypeError(msg));
13707     }
13708     return null;
13709 }
13710 exports.subscribeToResult = subscribeToResult;
13711
13712 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":158,"../symbol/observable":159,"./isArrayLike":169,"./isObject":173,"./isPromise":174,"./root":176}],178:[function(require,module,exports){
13713 "use strict";
13714 var Subscriber_1 = require('../Subscriber');
13715 var rxSubscriber_1 = require('../symbol/rxSubscriber');
13716 var Observer_1 = require('../Observer');
13717 function toSubscriber(nextOrObserver, error, complete) {
13718     if (nextOrObserver) {
13719         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
13720             return nextOrObserver;
13721         }
13722         if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
13723             return nextOrObserver[rxSubscriber_1.rxSubscriber]();
13724         }
13725     }
13726     if (!nextOrObserver && !error && !complete) {
13727         return new Subscriber_1.Subscriber(Observer_1.empty);
13728     }
13729     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
13730 }
13731 exports.toSubscriber = toSubscriber;
13732
13733 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":160}],179:[function(require,module,exports){
13734 "use strict";
13735 var errorObject_1 = require('./errorObject');
13736 var tryCatchTarget;
13737 function tryCatcher() {
13738     try {
13739         return tryCatchTarget.apply(this, arguments);
13740     }
13741     catch (e) {
13742         errorObject_1.errorObject.e = e;
13743         return errorObject_1.errorObject;
13744     }
13745 }
13746 function tryCatch(fn) {
13747     tryCatchTarget = fn;
13748     return tryCatcher;
13749 }
13750 exports.tryCatch = tryCatch;
13751 ;
13752
13753 },{"./errorObject":167}],180:[function(require,module,exports){
13754 // threejs.org/license
13755 (function(l,xa){"object"===typeof exports&&"undefined"!==typeof module?xa(exports):"function"===typeof define&&define.amd?define(["exports"],xa):xa(l.THREE=l.THREE||{})})(this,function(l){function xa(){}function C(a,b){this.x=a||0;this.y=b||0}function ba(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:hf++});this.uuid=Y.generateUUID();this.name="";this.image=void 0!==a?a:ba.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ba.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
13756 void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function fa(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Cb(a,b,c){this.uuid=Y.generateUUID();this.width=
13757 a;this.height=b;this.scissor=new fa(0,0,a,b);this.scissorTest=!1;this.viewport=new fa(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ba(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Db(a,b,c){Cb.call(this,a,b,c);this.activeMipMapLevel=
13758 this.activeCubeFace=0}function oa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function n(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function K(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function db(a,b,c,d,e,f,g,h,k,m,q,v){ba.call(this,null,f,g,h,k,m,d,e,q,v);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==
13759 m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Xa(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];ba.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Eb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=xe[e];void 0===f&&(f=new Float32Array(e),xe[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function ye(a,b){var c=ze[b];void 0===c&&(c=new Int32Array(b),ze[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}
13760 function jf(a,b){a.uniform1f(this.addr,b)}function kf(a,b){a.uniform1i(this.addr,b)}function lf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function mf(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,b)}function nf(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function of(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function pf(a,b){void 0===b.elements?
13761 a.uniformMatrix3fv(this.addr,!1,b):(Ae.set(b.elements),a.uniformMatrix3fv(this.addr,!1,Ae))}function qf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Be.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Be))}function rf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||Ce,d)}function sf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||De,d)}function Ee(a,b){a.uniform2iv(this.addr,b)}function Fe(a,b){a.uniform3iv(this.addr,b)}function Ge(a,
13762 b){a.uniform4iv(this.addr,b)}function tf(a){switch(a){case 5126:return jf;case 35664:return lf;case 35665:return mf;case 35666:return nf;case 35674:return of;case 35675:return pf;case 35676:return qf;case 35678:case 36198:return rf;case 35680:return sf;case 5124:case 35670:return kf;case 35667:case 35671:return Ee;case 35668:case 35672:return Fe;case 35669:case 35673:return Ge}}function uf(a,b){a.uniform1fv(this.addr,b)}function vf(a,b){a.uniform1iv(this.addr,b)}function wf(a,b){a.uniform2fv(this.addr,
13763 Eb(b,this.size,2))}function xf(a,b){a.uniform3fv(this.addr,Eb(b,this.size,3))}function yf(a,b){a.uniform4fv(this.addr,Eb(b,this.size,4))}function zf(a,b){a.uniformMatrix2fv(this.addr,!1,Eb(b,this.size,4))}function Af(a,b){a.uniformMatrix3fv(this.addr,!1,Eb(b,this.size,9))}function Bf(a,b){a.uniformMatrix4fv(this.addr,!1,Eb(b,this.size,16))}function Cf(a,b,c){var d=b.length,e=ye(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||Ce,e[a])}function Df(a,b,c){var d=b.length,e=ye(c,
13764 d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||De,e[a])}function Ef(a){switch(a){case 5126:return uf;case 35664:return wf;case 35665:return xf;case 35666:return yf;case 35674:return zf;case 35675:return Af;case 35676:return Bf;case 35678:return Cf;case 35680:return Df;case 5124:case 35670:return vf;case 35667:case 35671:return Ee;case 35668:case 35672:return Fe;case 35669:case 35673:return Ge}}function Ff(a,b,c){this.id=a;this.addr=c;this.setValue=tf(b.type)}function Gf(a,b,
13765 c){this.id=a;this.addr=c;this.size=b.size;this.setValue=Ef(b.type)}function He(a){this.id=a;this.seq=[];this.map={}}function eb(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=h.length;for(Pd.lastIndex=0;;){var m=Pd.exec(h),q=Pd.lastIndex,v=m[1],p=m[3];"]"===m[2]&&(v|=0);if(void 0===p||"["===p&&q+2===k){h=g;e=void 0===p?new Ff(v,e,f):new Gf(v,e,f);h.seq.push(e);
13766 h.map[e.id]=e;break}else p=g.map[v],void 0===p&&(p=new He(v),v=g,g=p,v.seq.push(g),v.map[g.id]=g),g=p}}}function G(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function fd(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function Hf(a,b){var c,d,e,f,g,h,k,m,q,v,p=a.context,r=a.state,l,t,y,x,u,H;this.render=function(w,I,W){if(0!==b.length){w=new n;var D=W.w/W.z,O=.5*W.z,aa=.5*W.w,F=16/W.w,ja=new C(F*D,F),T=new n(1,1,0),fb=new C(1,
13767 1),Ya=new fd;Ya.min.set(W.x,W.y);Ya.max.set(W.x+(W.z-16),W.y+(W.w-16));if(void 0===x){var F=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),ka=new Uint16Array([0,1,2,0,2,3]);l=p.createBuffer();t=p.createBuffer();p.bindBuffer(p.ARRAY_BUFFER,l);p.bufferData(p.ARRAY_BUFFER,F,p.STATIC_DRAW);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,t);p.bufferData(p.ELEMENT_ARRAY_BUFFER,ka,p.STATIC_DRAW);u=p.createTexture();H=p.createTexture();r.bindTexture(p.TEXTURE_2D,u);p.texImage2D(p.TEXTURE_2D,0,p.RGB,16,16,0,
13768 p.RGB,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);r.bindTexture(p.TEXTURE_2D,H);p.texImage2D(p.TEXTURE_2D,0,p.RGBA,16,16,0,p.RGBA,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);
13769 p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);var F=y={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nvUV = uv;\nvec2 pos = position;\nif ( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility =        visibility.r / 9.0;\nvVisibility *= 1.0 - visibility.g / 9.0;\nvVisibility *=       visibility.b / 9.0;\nvVisibility *= 1.0 - visibility.a / 9.0;\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
13770 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif ( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if ( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},ka=p.createProgram(),P=p.createShader(p.FRAGMENT_SHADER),
13771 M=p.createShader(p.VERTEX_SHADER),V="precision "+a.getPrecision()+" float;\n";p.shaderSource(P,V+F.fragmentShader);p.shaderSource(M,V+F.vertexShader);p.compileShader(P);p.compileShader(M);p.attachShader(ka,P);p.attachShader(ka,M);p.linkProgram(ka);x=ka;q=p.getAttribLocation(x,"position");v=p.getAttribLocation(x,"uv");c=p.getUniformLocation(x,"renderType");d=p.getUniformLocation(x,"map");e=p.getUniformLocation(x,"occlusionMap");f=p.getUniformLocation(x,"opacity");g=p.getUniformLocation(x,"color");
13772 h=p.getUniformLocation(x,"scale");k=p.getUniformLocation(x,"rotation");m=p.getUniformLocation(x,"screenPosition")}p.useProgram(x);r.initAttributes();r.enableAttribute(q);r.enableAttribute(v);r.disableUnusedAttributes();p.uniform1i(e,0);p.uniform1i(d,1);p.bindBuffer(p.ARRAY_BUFFER,l);p.vertexAttribPointer(q,2,p.FLOAT,!1,16,0);p.vertexAttribPointer(v,2,p.FLOAT,!1,16,8);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,t);r.disable(p.CULL_FACE);r.buffers.depth.setMask(!1);ka=0;for(P=b.length;ka<P;ka++)if(F=16/W.w,
13773 ja.set(F*D,F),M=b[ka],w.set(M.matrixWorld.elements[12],M.matrixWorld.elements[13],M.matrixWorld.elements[14]),w.applyMatrix4(I.matrixWorldInverse),w.applyMatrix4(I.projectionMatrix),T.copy(w),fb.x=W.x+T.x*O+O-8,fb.y=W.y+T.y*aa+aa-8,!0===Ya.containsPoint(fb)){r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,null);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,u);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGB,fb.x,fb.y,16,16,0);p.uniform1i(c,0);p.uniform2f(h,ja.x,ja.y);p.uniform3f(m,T.x,T.y,T.z);
13774 r.disable(p.BLEND);r.enable(p.DEPTH_TEST);p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0);r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,H);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGBA,fb.x,fb.y,16,16,0);p.uniform1i(c,1);r.disable(p.DEPTH_TEST);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,u);p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0);M.positionScreen.copy(T);M.customUpdateCallback?M.customUpdateCallback(M):M.updateLensFlares();p.uniform1i(c,2);r.enable(p.BLEND);for(var V=0,pa=M.lensFlares.length;V<
13775 pa;V++){var S=M.lensFlares[V];.001<S.opacity&&.001<S.scale&&(T.x=S.x,T.y=S.y,T.z=S.z,F=S.size*S.scale/W.w,ja.x=F*D,ja.y=F,p.uniform3f(m,T.x,T.y,T.z),p.uniform2f(h,ja.x,ja.y),p.uniform1f(k,S.rotation),p.uniform1f(f,S.opacity),p.uniform3f(g,S.color.r,S.color.g,S.color.b),r.setBlending(S.blending,S.blendEquation,S.blendSrc,S.blendDst),a.setTexture2D(S.texture,1),p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0))}}r.enable(p.CULL_FACE);r.enable(p.DEPTH_TEST);r.buffers.depth.setMask(!0);a.resetGLState()}}}
13776 function If(a,b){var c,d,e,f,g,h,k,m,q,v,p,r,l,t,y,x,u;function H(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var w=a.context,I=a.state,W,D,O,aa,F=new n,ja=new oa,T=new n;this.render=function(n,Ya){if(0!==b.length){if(void 0===O){var ka=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),P=new Uint16Array([0,1,2,0,2,3]);W=w.createBuffer();D=w.createBuffer();w.bindBuffer(w.ARRAY_BUFFER,W);w.bufferData(w.ARRAY_BUFFER,ka,w.STATIC_DRAW);
13777 w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,D);w.bufferData(w.ELEMENT_ARRAY_BUFFER,P,w.STATIC_DRAW);var ka=w.createProgram(),P=w.createShader(w.VERTEX_SHADER),M=w.createShader(w.FRAGMENT_SHADER);w.shaderSource(P,["precision "+a.getPrecision()+" float;","#define SHADER_NAME SpriteMaterial\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position * scale;\nvec2 rotatedPosition;\nrotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\nrotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\nvec4 finalPosition;\nfinalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition;\nfinalPosition = projectionMatrix * finalPosition;\ngl_Position = finalPosition;\n}"].join("\n"));
13778 w.shaderSource(M,["precision "+a.getPrecision()+" float;","#define SHADER_NAME SpriteMaterial\nuniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\nif ( texture.a < alphaTest ) discard;\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\nif ( fogType > 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n"));
13779 w.compileShader(P);w.compileShader(M);w.attachShader(ka,P);w.attachShader(ka,M);w.linkProgram(ka);O=ka;x=w.getAttribLocation(O,"position");u=w.getAttribLocation(O,"uv");c=w.getUniformLocation(O,"uvOffset");d=w.getUniformLocation(O,"uvScale");e=w.getUniformLocation(O,"rotation");f=w.getUniformLocation(O,"scale");g=w.getUniformLocation(O,"color");h=w.getUniformLocation(O,"map");k=w.getUniformLocation(O,"opacity");m=w.getUniformLocation(O,"modelViewMatrix");q=w.getUniformLocation(O,"projectionMatrix");
13780 v=w.getUniformLocation(O,"fogType");p=w.getUniformLocation(O,"fogDensity");r=w.getUniformLocation(O,"fogNear");l=w.getUniformLocation(O,"fogFar");t=w.getUniformLocation(O,"fogColor");y=w.getUniformLocation(O,"alphaTest");ka=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");ka.width=8;ka.height=8;P=ka.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);aa=new ba(ka);aa.needsUpdate=!0}w.useProgram(O);I.initAttributes();I.enableAttribute(x);I.enableAttribute(u);I.disableUnusedAttributes();
13781 I.disable(w.CULL_FACE);I.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,W);w.vertexAttribPointer(x,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(u,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,D);w.uniformMatrix4fv(q,!1,Ya.projectionMatrix.elements);I.activeTexture(w.TEXTURE0);w.uniform1i(h,0);P=ka=0;(M=n.fog)?(w.uniform3f(t,M.color.r,M.color.g,M.color.b),M.isFog?(w.uniform1f(r,M.near),w.uniform1f(l,M.far),w.uniform1i(v,1),P=ka=1):M.isFogExp2&&(w.uniform1f(p,M.density),w.uniform1i(v,2),P=ka=2)):
13782 (w.uniform1i(v,0),P=ka=0);for(var M=0,V=b.length;M<V;M++){var pa=b[M];pa.modelViewMatrix.multiplyMatrices(Ya.matrixWorldInverse,pa.matrixWorld);pa.z=-pa.modelViewMatrix.elements[14]}b.sort(H);for(var S=[],M=0,V=b.length;M<V;M++){var pa=b[M],N=pa.material;if(!1!==N.visible){pa.onBeforeRender(a,n,Ya,void 0,N,void 0);w.uniform1f(y,N.alphaTest);w.uniformMatrix4fv(m,!1,pa.modelViewMatrix.elements);pa.matrixWorld.decompose(F,ja,T);S[0]=T.x;S[1]=T.y;var C=0;n.fog&&N.fog&&(C=P);ka!==C&&(w.uniform1i(v,C),
13783 ka=C);null!==N.map?(w.uniform2f(c,N.map.offset.x,N.map.offset.y),w.uniform2f(d,N.map.repeat.x,N.map.repeat.y)):(w.uniform2f(c,0,0),w.uniform2f(d,1,1));w.uniform1f(k,N.opacity);w.uniform3f(g,N.color.r,N.color.g,N.color.b);w.uniform1f(e,N.rotation);w.uniform2fv(f,S);I.setBlending(N.blending,N.blendEquation,N.blendSrc,N.blendDst,N.blendEquationAlpha,N.blendSrcAlpha,N.blendDstAlpha,N.premultipliedAlpha);I.buffers.depth.setTest(N.depthTest);I.buffers.depth.setMask(N.depthWrite);N.map?a.setTexture2D(N.map,
13784 0):a.setTexture2D(aa,0);w.drawElements(w.TRIANGLES,6,w.UNSIGNED_SHORT,0);pa.onAfterRender(a,n,Ya,void 0,N,void 0)}}I.enable(w.CULL_FACE);a.resetGLState()}}}function U(){Object.defineProperty(this,"id",{value:Jf++});this.uuid=Y.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.shading=2;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=
13785 null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.needsUpdate=this.visible=!0}function ra(a){U.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
13786 this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),
13787 this.setValues(a))}function Za(a){U.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function Ra(a,b){this.min=void 0!==a?a:new n(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new n(-Infinity,-Infinity,-Infinity)}function Ea(a,b){this.center=void 0!==a?a:new n;this.radius=
13788 void 0!==b?b:0}function Ba(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function Aa(a,b){this.normal=void 0!==a?a:new n(1,0,0);this.constant=void 0!==b?b:0}function gd(a,b,c,d,e,f){this.planes=[void 0!==a?a:new Aa,void 0!==b?b:new Aa,void 0!==c?c:new Aa,void 0!==d?d:new Aa,void 0!==e?e:new Aa,void 0!==f?f:new Aa]}function Ie(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=t;var h=b.customDepthMaterial;
13789 d&&(g=y,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:f&&f.isGeometry&&(h=f.morphTargets&&0<f.morphTargets.length)),b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b),b=b.isSkinnedMesh&&c.skinning,f=0,h&&(f|=1),b&&(f|=2),g=g[f]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(f=
13790 g.uuid,h=c.uuid,b=x[f],void 0===b&&(b={},x[f]=b),f=b[h],void 0===f&&(f=g.clone(),b[h]=f),g=f);g.visible=c.visible;g.wireframe=c.wireframe;h=c.side;F.renderSingleSided&&2==h&&(h=0);F.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(b,d,g,h){if(!1!==b.visible){if(b.layers.test(d.layers)&&
13791 (b.isMesh||b.isLine||b.isPoints)&&b.castShadow&&(!b.frustumCulled||k.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,b.matrixWorld);var m=c.update(b),p=b.material;if(Array.isArray(p))for(var q=m.groups,v=0,r=q.length;v<r;v++){var u=q[v],w=p[u.materialIndex];w&&w.visible&&(w=e(b,w,h,l),a.renderBufferDirect(g,null,m,w,b,u))}else p.visible&&(w=e(b,p,h,l),a.renderBufferDirect(g,null,m,w,b,null))}b=b.children;m=0;for(p=b.length;m<p;m++)f(b[m],d,g,h)}}var g=a.context,h=a.state,
13792 k=new gd,m=new K,q=b.shadows,v=new C,p=new C(d.maxTextureSize,d.maxTextureSize),r=new n,l=new n,t=Array(4),y=Array(4),x={},u=[new n(1,0,0),new n(-1,0,0),new n(0,0,1),new n(0,0,-1),new n(0,1,0),new n(0,-1,0)],H=[new n(0,1,0),new n(0,1,0),new n(0,1,0),new n(0,1,0),new n(0,0,1),new n(0,0,-1)],w=[new fa,new fa,new fa,new fa,new fa,new fa];b=new Za;b.depthPacking=3201;b.clipping=!0;d=$a.distanceRGBA;for(var I=Ca.clone(d.uniforms),W=0;4!==W;++W){var D=0!==(W&1),O=0!==(W&2),aa=b.clone();aa.morphTargets=
13793 D;aa.skinning=O;t[W]=aa;D=new ra({defines:{USE_SHADOWMAP:""},uniforms:I,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:D,skinning:O,clipping:!0});y[W]=D}var F=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c){if(!1!==F.enabled&&(!1!==F.autoUpdate||!1!==F.needsUpdate)&&0!==q.length){h.disable(g.BLEND);h.buffers.color.setClear(1,1,1,1);h.buffers.depth.setTest(!0);h.setScissorTest(!1);
13794 for(var d,e=0,t=q.length;e<t;e++){var n=q[e];d=n.shadow;var y=n&&n.isPointLight;if(void 0===d)console.warn("THREE.WebGLShadowMap:",n,"has no shadow.");else{var x=d.camera;v.copy(d.mapSize);v.min(p);if(y){var D=v.x,I=v.y;w[0].set(2*D,I,D,I);w[1].set(0,I,D,I);w[2].set(3*D,I,D,I);w[3].set(D,I,D,I);w[4].set(3*D,0,D,I);w[5].set(D,0,D,I);v.x*=4;v.y*=2}null===d.map&&(d.map=new Cb(v.x,v.y,{minFilter:1003,magFilter:1003,format:1023}),d.map.texture.name=n.name+".shadowMap",x.updateProjectionMatrix());d.isSpotLightShadow&&
13795 d.update(n);D=d.map;I=d.matrix;l.setFromMatrixPosition(n.matrixWorld);x.position.copy(l);y?(d=6,I.makeTranslation(-l.x,-l.y,-l.z)):(d=1,r.setFromMatrixPosition(n.target.matrixWorld),x.lookAt(r),x.updateMatrixWorld(),I.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),I.multiply(x.projectionMatrix),I.multiply(x.matrixWorldInverse));a.setRenderTarget(D);a.clear();for(n=0;n<d;n++)y&&(r.copy(x.position),r.add(u[n]),x.up.copy(H[n]),x.lookAt(r),x.updateMatrixWorld(),h.viewport(w[n])),m.multiplyMatrices(x.projectionMatrix,
13796 x.matrixWorldInverse),k.setFromMatrix(m),f(b,c,x,y)}}e=a.getClearColor();t=a.getClearAlpha();a.setClearColor(e,t);F.needsUpdate=!1}}}function Kf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&(a=a.data);return b[a.uuid]},remove:function(c){c.isInterleavedBufferAttribute&&(c=c.data);var d=b[c.uuid];d&&(a.deleteBuffer(d.buffer),delete b[c.uuid])},update:function(c,d){c.isInterleavedBufferAttribute&&(c=c.data);var e=b[c.uuid];if(void 0===e){var e=c.uuid,f=c,g=f.array,h=f.dynamic?
13797 a.DYNAMIC_DRAW:a.STATIC_DRAW,k=a.createBuffer();a.bindBuffer(d,k);a.bufferData(d,g,h);f.onUploadCallback();h=a.FLOAT;g instanceof Float32Array?h=a.FLOAT:g instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):g instanceof Uint16Array?h=a.UNSIGNED_SHORT:g instanceof Int16Array?h=a.SHORT:g instanceof Uint32Array?h=a.UNSIGNED_INT:g instanceof Int32Array?h=a.INT:g instanceof Int8Array?h=a.BYTE:g instanceof Uint8Array&&(h=a.UNSIGNED_BYTE);b[e]={buffer:k,
13798 type:h,bytesPerElement:g.BYTES_PER_ELEMENT,version:f.version}}else e.version<c.version&&(f=c,g=f.array,k=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,g,a.STATIC_DRAW):-1===k.count?a.bufferSubData(d,0,g):0===k.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):(a.bufferSubData(d,k.offset*g.BYTES_PER_ELEMENT,g.subarray(k.offset,k.offset+
13799 k.count)),k.count=-1),e.version=c.version)}}}function ab(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||ab.DefaultOrder}function Qd(){this.mask=1}function z(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=Y.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=z.DefaultUp.clone();var a=new n,b=new ab,c=new oa,d=new n(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
13800 {position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new K},normalMatrix:{value:new Ba}});this.matrix=new K;this.matrixWorld=new K;this.matrixAutoUpdate=z.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Qd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={}}function Na(){z.call(this);this.type="Camera";this.matrixWorldInverse=
13801 new K;this.projectionMatrix=new K}function Fb(a,b,c,d,e,f){Na.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function qa(a,b,c,d){Na.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=
13802 0;this.updateProjectionMatrix()}function Sa(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new n;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new G;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function J(){Object.defineProperty(this,"id",{value:Rd++});this.uuid=Y.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=
13803 [];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function Z(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=Y.generateUUID();this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=
13804 !1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function pc(a,b){Z.call(this,new Int8Array(a),b)}function qc(a,b){Z.call(this,new Uint8Array(a),b)}function rc(a,b){Z.call(this,new Uint8ClampedArray(a),b)}function sc(a,b){Z.call(this,new Int16Array(a),b)}function gb(a,b){Z.call(this,new Uint16Array(a),b)}function tc(a,b){Z.call(this,new Int32Array(a),b)}function hb(a,b){Z.call(this,new Uint32Array(a),b)}function B(a,b){Z.call(this,new Float32Array(a),b)}function uc(a,
13805 b){Z.call(this,new Float64Array(a),b)}function Je(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Sd(a){if(0===a.length)return-Infinity;for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function E(){Object.defineProperty(this,
13806 "id",{value:Rd++});this.uuid=Y.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Gb(a,b,c,d,e,f){J.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new ib(a,b,c,d,e,f));this.mergeVertices()}function ib(a,b,c,d,e,f){function g(a,b,
13807 c,d,e,f,g,l,W,D,O){var aa=f/W,F=g/D,ja=f/2,T=g/2,C=l/2;g=W+1;var B=D+1,z=f=0,P,M,V=new n;for(M=0;M<B;M++){var pa=M*F-T;for(P=0;P<g;P++)V[a]=(P*aa-ja)*d,V[b]=pa*e,V[c]=C,m.push(V.x,V.y,V.z),V[a]=0,V[b]=0,V[c]=0<l?1:-1,q.push(V.x,V.y,V.z),v.push(P/W),v.push(1-M/D),f+=1}for(M=0;M<D;M++)for(P=0;P<W;P++)a=p+P+g*(M+1),b=p+(P+1)+g*(M+1),c=p+(P+1)+g*M,k.push(p+P+g*M,a,c),k.push(a,b,c),z+=6;h.addGroup(r,z,O);r+=z;p+=f}E.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,
13808 heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=[],m=[],q=[],v=[],p=0,r=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",new B(m,3));this.addAttribute("normal",new B(q,3));this.addAttribute("uv",new B(v,2))}function vc(a,b,c,d){J.call(this);this.type=
13809 "PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new jb(a,b,c,d));this.mergeVertices()}function jb(a,b,c,d){E.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||1;var g=c+1,h=d+1,k=a/c,m=b/d,q=[],v=[],p=[],r=[];for(a=0;a<h;a++){var l=a*m-f;for(b=0;b<g;b++)v.push(b*k-e,-l,0),p.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=
13810 0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,q.push(b+g*a,e,h),q.push(e,f,h);this.setIndex(q);this.addAttribute("position",new B(v,3));this.addAttribute("normal",new B(p,3));this.addAttribute("uv",new B(r,2))}function ya(a){U.call(this);this.type="MeshBasicMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=
13811 !1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=!1;this.setValues(a)}function kb(a,b){this.origin=void 0!==a?a:new n;this.direction=void 0!==b?b:new n}function Hb(a,b){this.start=void 0!==a?a:new n;this.end=void 0!==b?b:new n}function Ta(a,b,c){this.a=void 0!==a?a:new n;this.b=void 0!==b?b:new n;this.c=void 0!==c?c:new n}function la(a,b){z.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new E;this.material=void 0!==
13812 b?b:new ya({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Mf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new G(0),g=0,h,k,m,q;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,g)},render:function(b,d,r){b=b.background;null===b?e(f,g):b&&b.isColor&&(e(b,1),r=!0);(a.autoClear||r)&&a.clear(a.autoClearColor,a.autoClearDepth,
13813 a.autoClearStencil);b&&b.isCubeTexture?(void 0===m&&(m=new qa,q=new la(new ib(5,5,5),new ra({uniforms:$a.cube.uniforms,vertexShader:$a.cube.vertexShader,fragmentShader:$a.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}))),m.projectionMatrix.copy(d.projectionMatrix),m.matrixWorld.extractRotation(d.matrixWorld),m.matrixWorldInverse.getInverse(m.matrixWorld),q.material.uniforms.tCube.value=b,q.modelViewMatrix.multiplyMatrices(m.matrixWorldInverse,q.matrixWorld),c.update(q),a.renderBufferDirect(m,
13814 null,q.geometry,q.material,q,null)):b&&b.isTexture&&(void 0===h&&(h=new Fb(-1,1,1,-1,0,1),k=new la(new jb(2,2),new ya({depthTest:!1,depthWrite:!1,fog:!1}))),k.material.map=b,c.update(k),a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Nf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Of(a,b){return a.renderOrder!==
13815 b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Pf(){var a=[],b=-1,c=[],d=-1;return{opaque:a,transparent:c,init:function(){d=b=-1},push:function(e,f,g,h,k){var m,q;g.transparent?(m=c,q=++d):(m=a,q=++b);(q=m[q])?(q.id=e.id,q.object=e,q.geometry=f,q.material=g,q.program=g.program,q.renderOrder=e.renderOrder,q.z=h,q.group=k):(q={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},m.push(q))},finish:function(){a.length=b+1;c.length=
13816 d+1},sort:function(){a.sort(Nf);c.sort(Of)}}}function Qf(){var a={};return{get:function(b,c){var d=b.id+","+c.id,e=a[d];void 0===e&&(e=new Pf,a[d]=e);return e},dispose:function(){a={}}}}function Rf(a,b,c){var d,e,f;this.setMode=function(a){d=a};this.setIndex=function(a){e=a.type;f=a.bytesPerElement};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)};this.renderInstances=function(g,h,k){var m=b.get("ANGLE_instanced_arrays");null===m?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):
13817 (m.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=k*g.maxInstancedCount,d===a.TRIANGLES&&(c.faces+=g.maxInstancedCount*k/3))}}function Sf(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=f/3)};this.renderInstances=function(e,f,g){var h=b.get("ANGLE_instanced_arrays");if(null===h)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
13818 else{var k=e.attributes.position;k.isInterleavedBufferAttribute?(g=k.data.count,h.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount)):h.drawArraysInstancedANGLE(d,f,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*g/3)}}}function Tf(a,b,c){function d(a){a=a.target;var h=e[a.id];null!==h.index&&b.remove(h.index);for(var k in h.attributes)b.remove(h.attributes[k]);a.removeEventListener("dispose",d);delete e[a.id];if(k=f[a.id])b.remove(k),
13819 delete f[a.id];if(k=f[h.id])b.remove(k),delete f[h.id];c.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new E).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=
13820 c[f],e=0,q=d.length;e<q;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;var d=[],e=c.index,m=c.attributes;if(null!==e)for(var e=e.array,m=0,q=e.length;m<q;m+=3){var v=e[m+0],p=e[m+1],r=e[m+2];d.push(v,p,p,r,r,v)}else for(e=m.position.array,m=0,q=e.length/3-1;m<q;m+=3)v=m+0,p=m+1,r=m+2,d.push(v,p,p,r,r,v);d=new (65535<Sd(d)?hb:gb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Uf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];
13821 var c;switch(b.type){case "DirectionalLight":c={direction:new n,color:new G,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new n,direction:new n,color:new G,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new n,color:new G,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "HemisphereLight":c={direction:new n,skyColor:new G,
13822 groundColor:new G};break;case "RectAreaLight":c={color:new G,position:new n,halfWidth:new n,halfHeight:new n}}return a[b.id]=c}}}function Vf(a,b,c){var d={};return{update:function(a){var f=c.frame,g=a.geometry,h=b.get(a,g);d[h.id]!==f&&(g.isGeometry&&h.updateFromObject(a),b.update(h),d[h.id]=f);return h},clear:function(){d={}}}}function Wf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ke(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);
13823 !1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),Wf(c));return d}function Le(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD",
13824 "( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Td(a,b){var c=Le(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function Xf(a,b){var c=Le(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function Yf(a,b){var c;switch(b){case 1:c="Linear";break;case 2:c="Reinhard";break;case 3:c="Uncharted2";break;case 4:c="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+
13825 b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function Zf(a,b,c){a=a||{};return[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":
13826 ""].filter(wc).join("\n")}function $f(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function wc(a){return""!==a}function Me(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Ud(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/gm,function(a,c){var d=X[c];
13827 if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Ud(d)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function ag(a,b,c,d,e){var f=a.context,g=c.extensions,h=c.defines,k=d.vertexShader,m=d.fragmentShader,q="SHADOWMAP_TYPE_BASIC";1===e.shadowMapType?q="SHADOWMAP_TYPE_PCF":2===e.shadowMapType&&(q="SHADOWMAP_TYPE_PCF_SOFT");
13828 var v="ENVMAP_TYPE_CUBE",p="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(e.envMap){switch(c.envMap.mapping){case 301:case 302:v="ENVMAP_TYPE_CUBE";break;case 306:case 307:v="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:v="ENVMAP_TYPE_EQUIREC";break;case 305:v="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:p="ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var l=0<a.gammaFactor?
13829 a.gammaFactor:1,g=Zf(g,e,a.extensions),t=$f(h),n=f.createProgram();c.isRawShaderMaterial?(h=[t,"\n"].filter(wc).join("\n"),d=[g,t,"\n"].filter(wc).join("\n")):(h=["precision "+e.precision+" float;","precision "+e.precision+" int;","#define SHADER_NAME "+d.name,t,e.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+l,"#define MAX_BONES "+e.maxBones,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":
13830 "",e.envMap?"#define "+p:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.displacementMap&&e.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.vertexColors?"#define USE_COLOR":"",e.flatShading?
13831 "#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.useVertexTexture?"#define BONE_TEXTURE":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&!1===e.flatShading?"#define USE_MORPHNORMALS":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+e.numClippingPlanes,e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+q:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.logarithmicDepthBuffer?
13832 "#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;",
13833 "\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(wc).join("\n"),
13834 d=[g,"precision "+e.precision+" float;","precision "+e.precision+" int;","#define SHADER_NAME "+d.name,t,e.alphaTest?"#define ALPHATEST "+e.alphaTest:"","#define GAMMA_FACTOR "+l,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+v:"",e.envMap?"#define "+p:"",e.envMap?"#define "+r:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",
13835 e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.vertexColors?"#define USE_COLOR":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+e.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+
13836 (e.numClippingPlanes-e.numClipIntersection),e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+q:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",e.envMap&&a.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;",
13837 "uniform vec3 cameraPosition;",0!==e.toneMapping?"#define TONE_MAPPING":"",0!==e.toneMapping?X.tonemapping_pars_fragment:"",0!==e.toneMapping?Yf("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.outputEncoding||e.mapEncoding||e.envMapEncoding||e.emissiveMapEncoding?X.encodings_pars_fragment:"",e.mapEncoding?Td("mapTexelToLinear",e.mapEncoding):"",e.envMapEncoding?Td("envMapTexelToLinear",e.envMapEncoding):"",e.emissiveMapEncoding?Td("emissiveMapTexelToLinear",e.emissiveMapEncoding):
13838 "",e.outputEncoding?Xf("linearToOutputTexel",e.outputEncoding):"",e.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(wc).join("\n"));k=Ud(k);k=Me(k,e);m=Ud(m);m=Me(m,e);c.isShaderMaterial||(k=Ne(k),m=Ne(m));m=d+m;k=Ke(f,f.VERTEX_SHADER,h+k);m=Ke(f,f.FRAGMENT_SHADER,m);f.attachShader(n,k);f.attachShader(n,m);void 0!==c.index0AttributeName?f.bindAttribLocation(n,0,c.index0AttributeName):!0===e.morphTargets&&f.bindAttribLocation(n,0,"position");f.linkProgram(n);e=f.getProgramInfoLog(n);
13839 q=f.getShaderInfoLog(k);v=f.getShaderInfoLog(m);r=p=!0;if(!1===f.getProgramParameter(n,f.LINK_STATUS))p=!1,console.error("THREE.WebGLProgram: shader error: ",f.getError(),"gl.VALIDATE_STATUS",f.getProgramParameter(n,f.VALIDATE_STATUS),"gl.getProgramInfoLog",e,q,v);else if(""!==e)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",e);else if(""===q||""===v)r=!1;r&&(this.diagnostics={runnable:p,material:c,programLog:e,vertexShader:{log:q,prefix:h},fragmentShader:{log:v,prefix:d}});f.deleteShader(k);
13840 f.deleteShader(m);var x;this.getUniforms=function(){void 0===x&&(x=new eb(f,n,a));return x};var u;this.getAttributes=function(){if(void 0===u){for(var a={},b=f.getProgramParameter(n,f.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=f.getActiveAttrib(n,c).name;a[d]=f.getAttribLocation(n,d)}u=a}return u};this.destroy=function(){f.deleteProgram(n);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},
13841 attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=bg++;this.code=b;this.usedTimes=1;this.program=n;this.vertexShader=k;this.fragmentShader=m;return this}function cg(a,b){function c(a,b){var c;a?a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding):c=3E3;3E3===
13842 c&&b&&(c=3007);return c}var d=[],e={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},f="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking dithering".split(" ");
13843 this.getParameters=function(d,f,k,m,q,v){var p=e[d.type],r;if(v.isSkinnedMesh)if(r=v.skeleton.bones,b.floatVertexTextures)r=1024;else{var l=Math.min(Math.floor((b.maxVertexUniforms-20)/4),r.length);l<r.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+r.length+" bones. This GPU supports "+l+"."),r=0):r=l}else r=0;l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));
13844 var t=a.getRenderTarget();return{shaderID:p,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(t?t.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,
13845 displacementMap:!!d.displacementMap,roughnessMap:!!d.roughnessMap,metalnessMap:!!d.metalnessMap,specularMap:!!d.specularMap,alphaMap:!!d.alphaMap,gradientMap:!!d.gradientMap,combine:d.combine,vertexColors:d.vertexColors,fog:!!k,useFog:d.fog,fogExp:k&&k.isFogExp2,flatShading:1===d.shading,sizeAttenuation:d.sizeAttenuation,logarithmicDepthBuffer:b.logarithmicDepthBuffer,skinning:d.skinning&&0<r,maxBones:r,useVertexTexture:b.floatVertexTextures,morphTargets:d.morphTargets,morphNormals:d.morphNormals,
13846 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:q,dithering:d.dithering,shadowMapEnabled:a.shadowMap.enabled&&v.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,
13847 alphaTest:d.alphaTest,doubleSided:2===d.side,flipSided:1===d.side,depthPacking:void 0!==d.depthPacking?d.depthPacking:!1}};this.getProgramCode=function(b,c){var d=[];c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader));if(void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(e=0;e<f.length;e++)d.push(c[f[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(b,c,e,f){for(var q,v=0,p=d.length;v<
13848 p;v++){var r=d[v];if(r.code===f){q=r;++q.usedTimes;break}}void 0===q&&(q=new ag(a,f,b,c,e),d.push(q));return q};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=d.indexOf(a);d[b]=d[d.length-1];d.pop();a.destroy()}};this.programs=d}function dg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,
13849 0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Y.isPowerOfTwo(a.width)&&Y.isPowerOfTwo(a.height)}function m(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function q(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function v(b){b=b.target;b.removeEventListener("dispose",v);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);
13850 else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),
13851 c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,p){var q=d.get(b);if(0<b.version&&q.__version!==b.version){var r=b.image;if(void 0===r)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===r.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===q.__webglInit&&(q.__webglInit=!0,b.addEventListener("dispose",v),q.__webglTexture=
13852 a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_2D,q.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var t=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(t))if(r=t,r instanceof HTMLImageElement||r instanceof HTMLCanvasElement){var n=document.createElementNS("http://www.w3.org/1999/xhtml",
13853 "canvas");n.width=Y.nearestPowerOfTwo(r.width);n.height=Y.nearestPowerOfTwo(r.height);n.getContext("2d").drawImage(r,0,0,n.width,n.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+r.width+"x"+r.height+"). Resized to "+n.width+"x"+n.height,r);t=n}else t=r;var r=k(t),n=f(b.format),y=f(b.type);l(a.TEXTURE_2D,b,r);var aa=b.mipmaps;if(b.isDepthTexture){aa=a.DEPTH_COMPONENT;if(1015===b.type){if(!x)throw Error("Float Depth Texture only supported in WebGL2.0");aa=a.DEPTH_COMPONENT32F}else x&&
13854 (aa=a.DEPTH_COMPONENT16);1026===b.format&&aa===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,y=f(b.type));1027===b.format&&(aa=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,y=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,aa,t.width,t.height,0,n,y,null)}else if(b.isDataTexture)if(0<aa.length&&
13855 r){for(var F=0,ja=aa.length;F<ja;F++)t=aa[F],c.texImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,n,y,t.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,n,t.width,t.height,0,n,y,t.data);else if(b.isCompressedTexture)for(F=0,ja=aa.length;F<ja;F++)t=aa[F],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(n)?c.compressedTexImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,t.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
13856 c.texImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,n,y,t.data);else if(0<aa.length&&r){F=0;for(ja=aa.length;F<ja;F++)t=aa[F],c.texImage2D(a.TEXTURE_2D,F,n,n,y,t);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,n,n,y,t);m(b,r)&&a.generateMipmap(a.TEXTURE_2D);q.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_2D,q.__webglTexture)}function l(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f(g.wrapT)),
13857 a.texParameteri(c,a.TEXTURE_MAG_FILTER,f(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,q(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,q(g.minFilter)),
13858 1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=
13859 g.anisotropy)}function t(b,e,g,h){var k=f(e.texture.format),m=f(e.texture.type);c.texImage2D(h,0,k,e.width,e.height,0,k,m,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function n(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,
13860 b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var x="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=r;this.setTextureCube=function(b,p){var q=d.get(b);if(6===b.image.length)if(0<b.version&&q.__version!==
13861 b.version){q.__image__webglTextureCube||(b.addEventListener("dispose",v),q.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_CUBE_MAP,q.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var r=b&&b.isCompressedTexture,t=b.image[0]&&b.image[0].isDataTexture,n=[],y=0;6>y;y++)n[y]=r||t?t?b.image[y].image:b.image[y]:h(b.image[y],e.maxCubemapSize);var x=k(n[0]),F=f(b.format),ja=f(b.type);l(a.TEXTURE_CUBE_MAP,b,x);for(y=
13862 0;6>y;y++)if(r)for(var T,C=n[y].mipmaps,z=0,B=C.length;z<B;z++)T=C[z],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(F)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,z,F,T.width,T.height,0,T.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,z,F,T.width,T.height,0,F,ja,T.data);else t?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,0,F,n[y].width,n[y].height,
13863 0,F,ja,n[y].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,0,F,F,ja,n[y]);m(b,x)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);q.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+p),c.bindTexture(a.TEXTURE_CUBE_MAP,q.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",p);
13864 f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,q=k(b);if(h){e.__webglFramebuffer=[];for(var v=0;6>v;v++)e.__webglFramebuffer[v]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);l(a.TEXTURE_CUBE_MAP,b.texture,q);for(v=0;6>v;v++)t(e.__webglFramebuffer[v],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+v);m(b.texture,q)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,
13865 null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),l(a.TEXTURE_2D,b.texture,q),t(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,q)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,
13866 e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);r(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,
13867 a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),n(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),n(e.__webglDepthbuffer,
13868 b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);m(e,f)&&(b=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function eg(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function fg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();
13869 a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==u[b]&&(a.enable(b),u[b]=!0)}function f(b){!1!==u[b]&&(a.disable(b),u[b]=!1)}function g(b,d,g,h,k,m,p,q){0!==b?e(a.BLEND):f(a.BLEND);5===b||b===w&&q===ja||(2===b?q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),
13870 a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR)):4===b?q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR)):q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE_MINUS_SRC_ALPHA,
13871 a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)),w=b,ja=q);if(5===b){k=k||d;m=m||g;p=p||h;if(d!==I||k!==O)a.blendEquationSeparate(c(d),c(k)),I=d,O=k;if(g!==W||h!==D||m!==aa||p!==F)a.blendFuncSeparate(c(g),c(h),c(m),c(p)),W=g,D=h,aa=m,F=p}else F=aa=O=D=W=I=null}function h(b){T!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),T=b)}function k(b){0!==b?(e(a.CULL_FACE),b!==C&&(1===b?a.cullFace(a.BACK):
13872 2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);C=b}function m(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),B!==c||P!==d)a.polygonOffset(c,d),B=c,P=d}else f(a.POLYGON_OFFSET_FILL)}function q(b){void 0===b&&(b=a.TEXTURE0+V-1);S!==b&&(a.activeTexture(b),S=b)}var v=new function(){var b=!1,c=new fa,d=null,e=new fa;return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&
13873 (a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(0,0,0,1)}}},p=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);
13874 break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=null,d=null,g=null,h=null,k=null,m=null,p=null,q=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},
13875 setOp:function(b,c,d){if(k!==b||m!==c||p!==d)a.stencilOp(b,c,d),k=b,m=c,p=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=p=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=new Uint8Array(l),n=new Uint8Array(l),x=new Uint8Array(l),u={},H=null,w=null,I=null,W=null,D=null,O=null,aa=null,F=null,ja=!1,T=null,C=null,z=null,B=null,P=null,M=null,V=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),
13876 pa=1<=parseFloat(l),S=null,N={},E=new fa,G=new fa,K={};K[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);K[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:v,depth:p,stencil:r},init:function(){v.setClear(0,0,0,1);p.setClear(1);r.setClear(0);e(a.DEPTH_TEST);p.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=t.length;a<b;a++)t[a]=0},enableAttribute:function(c){t[c]=1;0===n[c]&&(a.enableVertexAttribArray(c),n[c]=
13877 1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){t[c]=1;0===n[c]&&(a.enableVertexAttribArray(c),n[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=0,c=n.length;b!==c;++b)n[b]!==t[b]&&(a.disableVertexAttribArray(b),n[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===H&&(H=[],b.get("WEBGL_compressed_texture_pvrtc")||
13878 b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)H.push(c[d]);return H},setBlending:g,setMaterial:function(b){2===b.side?f(a.CULL_FACE):e(a.CULL_FACE);h(1===b.side);!0===b.transparent?g(b.blending,b.blendEquation,b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);p.setFunc(b.depthFunc);p.setTest(b.depthTest);p.setMask(b.depthWrite);v.setMask(b.colorWrite);
13879 m(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==z&&(pa&&a.lineWidth(b),z=b)},setPolygonOffset:m,getScissorTest:function(){return M},setScissorTest:function(b){(M=b)?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:q,bindTexture:function(b,c){null===S&&q();var d=N[S];void 0===d&&(d={type:void 0,texture:void 0},N[S]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||K[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,
13880 arguments)}catch(b){console.error("THREE.WebGLState:",b)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(b){console.error("THREE.WebGLState:",b)}},scissor:function(b){!1===E.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),E.copy(b))},viewport:function(b){!1===G.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),G.copy(b))},reset:function(){for(var b=0;b<n.length;b++)1===n[b]&&(a.disableVertexAttribArray(b),n[b]=0);u={};S=H=null;N={};C=T=w=null;v.reset();p.reset();r.reset()}}}function gg(a,b,c){function d(b){if("highp"===
13881 b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=
13882 !0===c.logarithmicDepthBuffer&&!!b.get("EXT_frag_depth");var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),q=a.getParameter(a.MAX_VERTEX_ATTRIBS),v=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),p=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,t=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;
13883 var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:m,maxAttributes:q,maxVertexUniforms:v,maxVaryings:p,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:t,floatVertexTextures:l&&t}}function kd(a){qa.call(this);this.cameras=a||[]}function hg(a){var b=this,c=null,d=null;"VRFrameData"in window&&(d=new window.VRFrameData);
13884 var e=new K,f=new K,g=new K,h=new qa;h.bounds=new fa(0,0,.5,1);h.layers.enable(1);var k=new qa;k.bounds=new fa(.5,0,.5,1);k.layers.enable(2);var m=new kd([h,k]);m.layers.enable(1);m.layers.enable(2);var q,v;window.addEventListener("vrdisplaypresentchange",function(){if(c.isPresenting){var d=c.getEyeParameters("left"),e=d.renderWidth,d=d.renderHeight;v=a.getPixelRatio();q=a.getSize();a.setDrawingBufferSize(2*e,d,1)}else b.enabled&&a.setDrawingBufferSize(q.width,q.height,v)},!1);this.standing=this.enabled=
13885 !1;this.getDevice=function(){return c};this.setDevice=function(a){void 0!==a&&(c=a)};this.getCamera=function(a){if(null===c)return a;c.depthNear=a.near;c.depthFar=a.far;c.getFrameData(d);var b=d.pose;null!==b.position?a.position.fromArray(b.position):a.position.set(0,0,0);null!==b.orientation&&a.quaternion.fromArray(b.orientation);a.updateMatrixWorld();b=c.stageParameters;this.standing&&b&&(f.fromArray(b.sittingToStandingTransform),g.getInverse(f),a.matrixWorld.multiply(f),a.matrixWorldInverse.multiply(g));
13886 if(!1===c.isPresenting)return a;m.matrixWorld.copy(a.matrixWorld);m.matrixWorldInverse.copy(a.matrixWorldInverse);h.matrixWorldInverse.fromArray(d.leftViewMatrix);k.matrixWorldInverse.fromArray(d.rightViewMatrix);this.standing&&b&&(h.matrixWorldInverse.multiply(g),k.matrixWorldInverse.multiply(g));a=a.parent;null!==a&&(e.getInverse(a.matrixWorld),h.matrixWorldInverse.multiply(e),k.matrixWorldInverse.multiply(e));h.matrixWorld.getInverse(h.matrixWorldInverse);k.matrixWorld.getInverse(k.matrixWorldInverse);
13887 h.projectionMatrix.fromArray(d.leftProjectionMatrix);k.projectionMatrix.fromArray(d.rightProjectionMatrix);m.projectionMatrix.copy(h.projectionMatrix);a=c.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&h.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&k.bounds.fromArray(a.rightBounds));return m};this.getStandingMatrix=function(){return f};this.submitFrame=function(){c&&c.isPresenting&&c.submitFrame()}}function ig(a){var b={};return{get:function(c){if(void 0!==
13888 b[c])return b[c];var d;switch(c){case "WEBGL_depth_texture":d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||
13889 a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function jg(){function a(){m.value!==d&&(m.value=d,m.needsUpdate=0<e);c.numPlanes=
13890 e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=m.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Aa,k=new Ba,m={value:null,needsUpdate:!1};this.uniform=m;this.numIntersection=this.numPlanes=0;this.init=
13891 function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=!1;a()};this.setState=function(c,h,k,r,l,t){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,x=l.clippingState||null;m.value=x;x=b(c,r,n,t);for(c=0;c!==n;++c)x[c]=d[c];l.clippingState=x;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Xd(a){function b(){ga.init();ga.scissor(J.copy(ea).multiplyScalar(Q));
13892 ga.viewport(U.copy(hd).multiplyScalar(Q))}function c(){S=G=null;pa="";V=-1;ga.reset()}function d(a){a.preventDefault();c();b();ha.clear();xa.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ha.remove(a)}function f(a){var b=ha.get(a).program;a.program=void 0;void 0!==b&&va.releaseProgram(b)}function g(a,b,c){a.render(function(a){B.renderBufferImmediate(a,b,c)})}function h(a,b){return Math.abs(b[0])-Math.abs(a[0])}function k(a,b,c){if(a.visible){if(a.layers.test(b.layers))if(a.isLight)aa.push(a);
13893 else if(a.isSprite)a.frustumCulled&&!Vd.intersectsSprite(a)||C.push(a);else if(a.isLensFlare)z.push(a);else if(a.isImmediateRenderObject)c&&Oa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(jd),F.push(a,null,a.material,Oa.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||Vd.intersectsObject(a)){c&&Oa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(jd);var d=xa.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<
13894 h;g++){var m=f[g],q=e[m.materialIndex];q&&q.visible&&F.push(a,d,q,Oa.z,m)}else e.visible&&F.push(a,d,e,Oa.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function m(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d,g=g.group;if(c.isArrayCamera){N=c;for(var p=c.cameras,v=0,r=p.length;v<r;v++){var l=p[v];if(h.layers.test(l.layers)){var t=l.bounds,n=t.x*ba,ca=t.y*L,u=t.z*ba,t=t.w*L;B.setViewport(n,ca,u,t);B.setScissor(n,ca,u,t);B.setScissorTest(!0);
13895 q(h,b,l,k,m,g)}}}else N=null,q(h,b,c,k,m,g)}}function q(a,b,c,d,e,f){a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);a.onBeforeRender(B,b,c,d,e,f);if(a.isImmediateRenderObject){ga.setMaterial(e);var h=p(c,b.fog,e,a);pa="";g(a,h,e)}else B.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(B,b,c,d,e,f)}function v(a,b,c){var d=ha.get(a);c=va.getParameters(a,da,b,Ha.numPlanes,Ha.numIntersection,c);var g=va.getProgramCode(a,c),h=
13896 d.program,k=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;k=!1}k&&(c.shaderID?(h=$a[c.shaderID],d.shader={name:a.type,uniforms:Ca.clone(h.uniforms),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader),h=va.acquireProgram(a,d.shader,c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=
13897 a.numSupportedMorphTargets=0;g<B.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=0;g<B.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Ha.numPlanes,d.numIntersection=Ha.numIntersection,c.clippingPlanes=Ha.uniform;d.fog=b;d.lightsHash=da.hash;a.lights&&(c.ambientLightColor.value=da.ambient,c.directionalLights.value=
13898 da.directional,c.spotLights.value=da.spot,c.rectAreaLights.value=da.rectArea,c.pointLights.value=da.point,c.hemisphereLights.value=da.hemi,c.directionalShadowMap.value=da.directionalShadowMap,c.directionalShadowMatrix.value=da.directionalShadowMatrix,c.spotShadowMap.value=da.spotShadowMap,c.spotShadowMatrix.value=da.spotShadowMatrix,c.pointShadowMap.value=da.pointShadowMap,c.pointShadowMatrix.value=da.pointShadowMatrix);a=d.program.getUniforms();a=eb.seqWithValue(a.seq,c);d.uniformsList=a}function p(a,
13899 b,c,d){X=0;var e=ha.get(c);id&&(Wd||a!==S)&&Ha.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,e,a===S&&c.id===V);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==da.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Ha.numPlanes&&e.numIntersection===Ha.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(v(c,b,d),c.needsUpdate=!1);var f=!1,g=!1,h=!1,k=e.program,m=k.getUniforms(),q=e.shader.uniforms;
13900 k.id!==G&&(A.useProgram(k.program),G=k.id,h=g=f=!0);c.id!==V&&(V=c.id,g=!0);if(f||a!==S){m.setValue(A,"projectionMatrix",a.projectionMatrix);ia.logarithmicDepthBuffer&&m.setValue(A,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));S!==(N||a)&&(S=N||a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=m.map.cameraPosition,void 0!==f&&f.setValue(A,Oa.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||
13901 c.isShaderMaterial||c.skinning)&&m.setValue(A,"viewMatrix",a.matrixWorldInverse)}if(c.skinning&&(m.setOptional(A,d,"bindMatrix"),m.setOptional(A,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,ia.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=Y.nextPowerOfTwo(Math.ceil(f)),f=Math.max(f,4),p=new Float32Array(f*f*4);p.set(a.boneMatrices);var t=new db(p,f,f,1023,1015);a.boneMatrices=p;a.boneTexture=t;a.boneTextureSize=f}m.setValue(A,"boneTexture",a.boneTexture);m.setValue(A,
13902 "boneTextureSize",a.boneTextureSize)}else m.setOptional(A,a,"boneMatrices");if(g){m.setValue(A,"toneMappingExposure",B.toneMappingExposure);m.setValue(A,"toneMappingWhitePoint",B.toneMappingWhitePoint);c.lights&&(g=h,q.ambientLightColor.needsUpdate=g,q.directionalLights.needsUpdate=g,q.pointLights.needsUpdate=g,q.spotLights.needsUpdate=g,q.rectAreaLights.needsUpdate=g,q.hemisphereLights.needsUpdate=g);b&&c.fog&&(q.fogColor.value=b.color,b.isFog?(q.fogNear.value=b.near,q.fogFar.value=b.far):b.isFogExp2&&
13903 (q.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){q.opacity.value=c.opacity;q.diffuse.value=c.color;c.emissive&&q.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);q.map.value=c.map;q.specularMap.value=c.specularMap;q.alphaMap.value=c.alphaMap;c.lightMap&&(q.lightMap.value=c.lightMap,q.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(q.aoMap.value=
13904 c.aoMap,q.aoMapIntensity.value=c.aoMapIntensity);var n;c.map?n=c.map:c.specularMap?n=c.specularMap:c.displacementMap?n=c.displacementMap:c.normalMap?n=c.normalMap:c.bumpMap?n=c.bumpMap:c.roughnessMap?n=c.roughnessMap:c.metalnessMap?n=c.metalnessMap:c.alphaMap?n=c.alphaMap:c.emissiveMap&&(n=c.emissiveMap);void 0!==n&&(n.isWebGLRenderTarget&&(n=n.texture),b=n.offset,n=n.repeat,q.offsetRepeat.value.set(b.x,b.y,n.x,n.y));q.envMap.value=c.envMap;q.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;
13905 q.reflectivity.value=c.reflectivity;q.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity):c.isLineDashedMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.dashSize.value=c.dashSize,q.totalSize.value=c.dashSize+c.gapSize,q.scale.value=c.scale):c.isPointsMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.size.value=c.size*Q,q.scale.value=.5*L,q.map.value=c.map,null!==c.map&&(n=c.map.offset,c=c.map.repeat,q.offsetRepeat.value.set(n.x,
13906 n.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(r(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?r(q,c):c.isMeshPhysicalMaterial?(q.clearCoat.value=c.clearCoat,q.clearCoatRoughness.value=c.clearCoatRoughness,l(q,c)):c.isMeshStandardMaterial?l(q,c):c.isMeshDepthMaterial?c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias):
13907 c.isMeshNormalMaterial&&(c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias));void 0!==q.ltcMat&&(q.ltcMat.value=R.LTC_MAT_TEXTURE);void 0!==q.ltcMag&&(q.ltcMag.value=R.LTC_MAG_TEXTURE);eb.upload(A,e.uniformsList,q,B)}m.setValue(A,"modelViewMatrix",
13908 d.modelViewMatrix);m.setValue(A,"normalMatrix",d.normalMatrix);m.setValue(A,"modelMatrix",d.matrixWorld);return k}function r(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,
13909 a.displacementBias.value=b.displacementBias)}function l(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=
13910 b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function t(a,b){var c,d,e,f,g=0,h=0,k=0,m,q,p,v=b.matrixWorldInverse,r=0,l=0,n=0,t=0,ca=0;c=0;for(d=a.length;c<d;c++)if(e=a[c],f=e.color,m=e.intensity,q=e.distance,p=e.shadow&&e.shadow.map?e.shadow.map.texture:null,e.isAmbientLight)g+=f.r*m,h+=f.g*m,k+=f.b*m;else if(e.isDirectionalLight){var u=wa.get(e);u.color.copy(e.color).multiplyScalar(e.intensity);u.direction.setFromMatrixPosition(e.matrixWorld);
13911 Oa.setFromMatrixPosition(e.target.matrixWorld);u.direction.sub(Oa);u.direction.transformDirection(v);if(u.shadow=e.castShadow)f=e.shadow,u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.directionalShadowMap[r]=p;da.directionalShadowMatrix[r]=e.shadow.matrix;da.directional[r]=u;r++}else if(e.isSpotLight){u=wa.get(e);u.position.setFromMatrixPosition(e.matrixWorld);u.position.applyMatrix4(v);u.color.copy(f).multiplyScalar(m);u.distance=q;u.direction.setFromMatrixPosition(e.matrixWorld);
13912 Oa.setFromMatrixPosition(e.target.matrixWorld);u.direction.sub(Oa);u.direction.transformDirection(v);u.coneCos=Math.cos(e.angle);u.penumbraCos=Math.cos(e.angle*(1-e.penumbra));u.decay=0===e.distance?0:e.decay;if(u.shadow=e.castShadow)f=e.shadow,u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.spotShadowMap[n]=p;da.spotShadowMatrix[n]=e.shadow.matrix;da.spot[n]=u;n++}else if(e.isRectAreaLight)u=wa.get(e),u.color.copy(f).multiplyScalar(m/(e.width*e.height)),u.position.setFromMatrixPosition(e.matrixWorld),
13913 u.position.applyMatrix4(v),oa.identity(),qa.copy(e.matrixWorld),qa.premultiply(v),oa.extractRotation(qa),u.halfWidth.set(.5*e.width,0,0),u.halfHeight.set(0,.5*e.height,0),u.halfWidth.applyMatrix4(oa),u.halfHeight.applyMatrix4(oa),da.rectArea[t]=u,t++;else if(e.isPointLight){u=wa.get(e);u.position.setFromMatrixPosition(e.matrixWorld);u.position.applyMatrix4(v);u.color.copy(e.color).multiplyScalar(e.intensity);u.distance=e.distance;u.decay=0===e.distance?0:e.decay;if(u.shadow=e.castShadow)f=e.shadow,
13914 u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.pointShadowMap[l]=p;da.pointShadowMatrix[l]=e.shadow.matrix;da.point[l]=u;l++}else e.isHemisphereLight&&(u=wa.get(e),u.direction.setFromMatrixPosition(e.matrixWorld),u.direction.transformDirection(v),u.direction.normalize(),u.skyColor.copy(e.color).multiplyScalar(m),u.groundColor.copy(e.groundColor).multiplyScalar(m),da.hemi[ca]=u,ca++);da.ambient[0]=g;da.ambient[1]=h;da.ambient[2]=k;da.directional.length=r;da.spot.length=n;
13915 da.rectArea.length=t;da.point.length=l;da.hemi.length=ca;da.hash=r+","+l+","+n+","+t+","+ca+","+da.shadows.length}function y(a){var b;if(1E3===a)return A.REPEAT;if(1001===a)return A.CLAMP_TO_EDGE;if(1002===a)return A.MIRRORED_REPEAT;if(1003===a)return A.NEAREST;if(1004===a)return A.NEAREST_MIPMAP_NEAREST;if(1005===a)return A.NEAREST_MIPMAP_LINEAR;if(1006===a)return A.LINEAR;if(1007===a)return A.LINEAR_MIPMAP_NEAREST;if(1008===a)return A.LINEAR_MIPMAP_LINEAR;if(1009===a)return A.UNSIGNED_BYTE;if(1017===
13916 a)return A.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return A.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return A.UNSIGNED_SHORT_5_6_5;if(1010===a)return A.BYTE;if(1011===a)return A.SHORT;if(1012===a)return A.UNSIGNED_SHORT;if(1013===a)return A.INT;if(1014===a)return A.UNSIGNED_INT;if(1015===a)return A.FLOAT;if(1016===a&&(b=ma.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return A.ALPHA;if(1022===a)return A.RGB;if(1023===a)return A.RGBA;if(1024===a)return A.LUMINANCE;if(1025===a)return A.LUMINANCE_ALPHA;
13917 if(1026===a)return A.DEPTH_COMPONENT;if(1027===a)return A.DEPTH_STENCIL;if(100===a)return A.FUNC_ADD;if(101===a)return A.FUNC_SUBTRACT;if(102===a)return A.FUNC_REVERSE_SUBTRACT;if(200===a)return A.ZERO;if(201===a)return A.ONE;if(202===a)return A.SRC_COLOR;if(203===a)return A.ONE_MINUS_SRC_COLOR;if(204===a)return A.SRC_ALPHA;if(205===a)return A.ONE_MINUS_SRC_ALPHA;if(206===a)return A.DST_ALPHA;if(207===a)return A.ONE_MINUS_DST_ALPHA;if(208===a)return A.DST_COLOR;if(209===a)return A.ONE_MINUS_DST_COLOR;
13918 if(210===a)return A.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ma.get("WEBGL_compressed_texture_s3tc"),null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ma.get("WEBGL_compressed_texture_pvrtc"),null!==b){if(2100===a)return b.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===a)return b.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
13919 if(2102===a)return b.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===a)return b.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===a&&(b=ma.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ma.get("EXT_blend_minmax"),null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ma.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","86");a=a||{};var x=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml",
13920 "canvas"),u=void 0!==a.context?a.context:null,H=void 0!==a.alpha?a.alpha:!1,w=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,W=void 0!==a.antialias?a.antialias:!1,D=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,O=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,aa=[],F=null,ja=new Float32Array(8),C=[],z=[];this.domElement=x;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=
13921 !1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var B=this,G=null,P=null,M=null,V=-1,pa="",S=null,N=null,J=new fa,Z=null,U=new fa,X=0,ba=x.width,L=x.height,Q=1,ea=new fa(0,0,ba,L),na=!1,hd=new fa(0,0,ba,L),Vd=new gd,Ha=new jg,id=!1,Wd=!1,jd=new K,Oa=new n,qa=new K,oa=new K,da={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],
13922 spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},ta={geometries:0,textures:0},la={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:la,memory:ta,programs:null};var A;try{H={alpha:H,depth:w,stencil:I,antialias:W,premultipliedAlpha:D,preserveDrawingBuffer:O};A=u||x.getContext("webgl",H)||x.getContext("experimental-webgl",H);if(null===A){if(null!==x.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";
13923 throw"Error creating WebGL context.";}void 0===A.getShaderPrecisionFormat&&(A.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});x.addEventListener("webglcontextlost",d,!1)}catch(kg){console.error("THREE.WebGLRenderer: "+kg)}var ma=new ig(A);ma.get("WEBGL_depth_texture");ma.get("OES_texture_float");ma.get("OES_texture_float_linear");ma.get("OES_texture_half_float");ma.get("OES_texture_half_float_linear");ma.get("OES_standard_derivatives");ma.get("ANGLE_instanced_arrays");
13924 ma.get("OES_element_index_uint")&&(E.MaxIndex=4294967296);var ia=new gg(A,ma,a),ga=new fg(A,ma,y),ha=new eg,ra=new dg(A,ma,ga,ha,ia,y,ta),ua=new Kf(A),za=new Tf(A,ua,ta),xa=new Vf(A,za,la),va=new cg(this,ia),wa=new Uf,Aa=new Qf,ya=new Mf(this,ga,xa,D),sa=new hg(this);this.info.programs=va.programs;var Da=new Sf(A,ma,la),Ea=new Rf(A,ma,la);b();this.context=A;this.capabilities=ia;this.extensions=ma;this.properties=ha;this.renderLists=Aa;this.state=ga;this.vr=sa;var Ba=new Ie(this,da,xa,ia);this.shadowMap=
13925 Ba;var Fa=new If(this,C),Ga=new Hf(this,z);this.getContext=function(){return A};this.getContextAttributes=function(){return A.getContextAttributes()};this.forceContextLoss=function(){var a=ma.get("WEBGL_lose_context");a&&a.loseContext()};this.getMaxAnisotropy=function(){return ia.getMaxAnisotropy()};this.getPrecision=function(){return ia.precision};this.getPixelRatio=function(){return Q};this.setPixelRatio=function(a){void 0!==a&&(Q=a,this.setSize(ba,L,!1))};this.getSize=function(){return{width:ba,
13926 height:L}};this.setSize=function(a,b,c){var d=sa.getDevice();d&&d.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(ba=a,L=b,x.width=a*Q,x.height=b*Q,!1!==c&&(x.style.width=a+"px",x.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:ba*Q,height:L*Q}};this.setDrawingBufferSize=function(a,b,c){ba=a;L=b;Q=c;x.width=a*c;x.height=b*c;this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){hd.set(a,L-
13927 b-d,c,d);ga.viewport(U.copy(hd).multiplyScalar(Q))};this.setScissor=function(a,b,c,d){ea.set(a,L-b-d,c,d);ga.scissor(J.copy(ea).multiplyScalar(Q))};this.setScissorTest=function(a){ga.setScissorTest(na=a)};this.getClearColor=ya.getClearColor;this.setClearColor=ya.setClearColor;this.getClearAlpha=ya.getClearAlpha;this.setClearAlpha=ya.setClearAlpha;this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=A.COLOR_BUFFER_BIT;if(void 0===b||b)d|=A.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=A.STENCIL_BUFFER_BIT;
13928 A.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.resetGLState=c;this.dispose=function(){x.removeEventListener("webglcontextlost",d,!1);Aa.dispose()};this.renderBufferImmediate=function(a,b,c){ga.initAttributes();var d=ha.get(a);a.hasPositions&&!d.position&&(d.position=A.createBuffer());a.hasNormals&&!d.normal&&
13929 (d.normal=A.createBuffer());a.hasUvs&&!d.uv&&(d.uv=A.createBuffer());a.hasColors&&!d.color&&(d.color=A.createBuffer());b=b.getAttributes();a.hasPositions&&(A.bindBuffer(A.ARRAY_BUFFER,d.position),A.bufferData(A.ARRAY_BUFFER,a.positionArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.position),A.vertexAttribPointer(b.position,3,A.FLOAT,!1,0,0));if(a.hasNormals){A.bindBuffer(A.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&1===c.shading)for(var e=0,f=
13930 3*a.count;e<f;e+=9){var g=a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,k=(g[e+1]+g[e+4]+g[e+7])/3,m=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=k;g[e+2]=m;g[e+3]=h;g[e+4]=k;g[e+5]=m;g[e+6]=h;g[e+7]=k;g[e+8]=m}A.bufferData(A.ARRAY_BUFFER,a.normalArray,A.DYNAMIC_DRAW);ga.enableAttribute(b.normal);A.vertexAttribPointer(b.normal,3,A.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(A.bindBuffer(A.ARRAY_BUFFER,d.uv),A.bufferData(A.ARRAY_BUFFER,a.uvArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.uv),A.vertexAttribPointer(ua.uv,2,A.FLOAT,
13931 !1,0,0));a.hasColors&&0!==c.vertexColors&&(A.bindBuffer(A.ARRAY_BUFFER,d.color),A.bufferData(A.ARRAY_BUFFER,a.colorArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.color),A.vertexAttribPointer(b.color,3,A.FLOAT,!1,0,0));ga.disableUnusedAttributes();A.drawArrays(A.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){ga.setMaterial(d);var g=p(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var k=!1;a!==pa&&(pa=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var q=
13932 b.length;a<q;a++)k=b[a],m.push([k,a]);m.sort(h);8<m.length&&(m.length=8);var v=c.morphAttributes;a=0;for(q=m.length;a<q;a++)k=m[a],ja[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&v.position&&c.addAttribute("morphTarget"+a,v.position[b]),!0===d.morphNormals&&v.normal&&c.addAttribute("morphNormal"+a,v.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=ja.length;a<b;a++)ja[a]=0;g.getUniforms().setValue(A,"morphTargetInfluences",
13933 ja);k=!0}b=c.index;q=c.attributes.position;m=1;!0===d.wireframe&&(b=za.getWireframeAttribute(c),m=2);var r;a=Da;null!==b&&(r=ua.get(b),a=Ea,a.setIndex(r));if(k){k=void 0;if(c&&c.isInstancedBufferGeometry&&null===ma.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===k&&(k=0);ga.initAttributes();var v=c.attributes,g=g.getAttributes(),l=d.defaultAttributeValues,
13934 n;for(n in g){var t=g[n];if(0<=t){var u=v[n];if(void 0!==u){var ca=u.normalized,w=u.itemSize,x=ua.get(u),y=x.buffer,H=x.type,x=x.bytesPerElement;if(u.isInterleavedBufferAttribute){var I=u.data,D=I.stride,u=u.offset;I&&I.isInstancedInterleavedBuffer?(ga.enableAttributeAndDivisor(t,I.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=I.meshPerAttribute*I.count)):ga.enableAttribute(t);A.bindBuffer(A.ARRAY_BUFFER,y);A.vertexAttribPointer(t,w,H,ca,D*x,(k*D+u)*x)}else u.isInstancedBufferAttribute?
13935 (ga.enableAttributeAndDivisor(t,u.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):ga.enableAttribute(t),A.bindBuffer(A.ARRAY_BUFFER,y),A.vertexAttribPointer(t,w,H,ca,0,k*w*x)}else if(void 0!==l&&(ca=l[n],void 0!==ca))switch(ca.length){case 2:A.vertexAttrib2fv(t,ca);break;case 3:A.vertexAttrib3fv(t,ca);break;case 4:A.vertexAttrib4fv(t,ca);break;default:A.vertexAttrib1fv(t,ca)}}}ga.disableUnusedAttributes()}null!==b&&A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,
13936 r.buffer)}r=0;null!==b?r=b.count:void 0!==q&&(r=q.count);b=c.drawRange.start*m;q=null!==f?f.start*m:0;n=Math.max(b,q);f=Math.max(0,Math.min(r,b+c.drawRange.count*m,q+(null!==f?f.count*m:Infinity))-1-n+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ga.setLineWidth(d.wireframeLinewidth*(null===P?Q:1)),a.setMode(A.LINES);else switch(e.drawMode){case 0:a.setMode(A.TRIANGLES);break;case 1:a.setMode(A.TRIANGLE_STRIP);break;case 2:a.setMode(A.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ga.setLineWidth(d*
13937 (null===P?Q:1)),e.isLineSegments?a.setMode(A.LINES):e.isLineLoop?a.setMode(A.LINE_LOOP):a.setMode(A.LINE_STRIP)):e.isPoints&&a.setMode(A.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,n,f):a.render(n,f)}};this.compile=function(a,b){aa=[];a.traverse(function(a){a.isLight&&aa.push(a)});t(aa,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)v(b.material[c],a.fog,b);else v(b.material,a.fog,b)})};this.animate=function(a){function b(){a();
13938 (sa.getDevice()||window).requestAnimationFrame(b)}(sa.getDevice()||window).requestAnimationFrame(b)};this.render=function(a,b,c,d){if(b&&b.isCamera){pa="";V=-1;S=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();sa.enabled&&(b=sa.getCamera(b));jd.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);Vd.setFromMatrix(jd);aa.length=0;C.length=0;z.length=0;Wd=this.localClippingEnabled;id=Ha.init(this.clippingPlanes,Wd,b);F=Aa.get(a,b);F.init();k(a,b,B.sortObjects);
13939 F.finish();!0===B.sortObjects&&F.sort();id&&Ha.beginShadows();for(var e=aa,f=0,g=0,h=e.length;g<h;g++){var q=e[g];q.castShadow&&(da.shadows[f]=q,f++)}da.shadows.length=f;Ba.render(a,b);t(aa,b);id&&Ha.endShadows();la.frame++;la.calls=0;la.vertices=0;la.faces=0;la.points=0;void 0===c&&(c=null);this.setRenderTarget(c);ya.render(a,b,d);d=F.opaque;e=F.transparent;a.overrideMaterial?(f=a.overrideMaterial,d.length&&m(d,a,b,f),e.length&&m(e,a,b,f)):(d.length&&m(d,a,b),e.length&&m(e,a,b));Fa.render(a,b);Ga.render(a,
13940 b,U);c&&ra.updateRenderTargetMipmap(c);ga.buffers.depth.setTest(!0);ga.buffers.depth.setMask(!0);ga.buffers.color.setMask(!0);b.isArrayCamera&&B.setScissorTest(!1);sa.enabled&&sa.submitFrame()}else console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.")};this.setFaceCulling=function(a,b){ga.setCullFace(a);ga.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=X;a>=ia.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+
13941 ia.maxTextures);X+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);ra.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);ra.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=
13942 !1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?ra.setTextureCube(b,c):ra.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return P};this.setRenderTarget=function(a){(P=a)&&void 0===ha.get(a).__webglFramebuffer&&ra.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,
13943 c;a?(c=ha.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,J.copy(a.scissor),Z=a.scissorTest,U.copy(a.viewport)):(c=null,J.copy(ea).multiplyScalar(Q),Z=na,U.copy(hd).multiplyScalar(Q));M!==c&&(A.bindFramebuffer(A.FRAMEBUFFER,c),M=c);ga.scissor(J);ga.setScissorTest(Z);ga.viewport(U);b&&(b=ha.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=
13944 function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=ha.get(a).__webglFramebuffer;if(g){var h=!1;g!==M&&(A.bindFramebuffer(A.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,q=k.type;1023!==m&&y(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===q||y(q)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===q&&(ma.get("OES_texture_float")||ma.get("WEBGL_color_buffer_float"))||
13945 1016===q&&ma.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,y(m),y(q),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&A.bindFramebuffer(A.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}}
13946 function Ib(a,b){this.name="";this.color=new G(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,b,c){this.name="";this.color=new G(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function ld(){z.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Yd(a,b,c,d,e){z.call(this);this.lensFlares=[];this.positionScreen=new n;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function bb(a){U.call(this);this.type="SpriteMaterial";
13947 this.color=new G(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function xc(a){z.call(this);this.type="Sprite";this.material=void 0!==a?a:new bb}function yc(){z.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function zc(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else{console.warn("THREE.Skeleton boneInverses is the wrong length.");
13948 this.boneInverses=[];for(var c=0,d=this.bones.length;c<d;c++)this.boneInverses.push(new K)}}function md(){z.call(this);this.type="Bone"}function nd(a,b){la.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new K;this.bindMatrixInverse=new K;var c=this.initBones(),c=new zc(c);this.bind(c,this.matrixWorld);this.normalizeSkinWeights()}function ea(a){U.call(this);this.type="LineBasicMaterial";this.color=new G(16777215);this.linewidth=1;this.linejoin=this.linecap="round";
13949 this.lights=!1;this.setValues(a)}function sa(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new Q(a,b);z.call(this);this.type="Line";this.geometry=void 0!==a?a:new E;this.material=void 0!==b?b:new ea({color:16777215*Math.random()})}function Q(a,b){sa.call(this,a,b);this.type="LineSegments"}function od(a,b){sa.call(this,a,b);this.type="LineLoop"}function Fa(a){U.call(this);this.type="PointsMaterial";this.color=
13950 new G(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Kb(a,b){z.call(this);this.type="Points";this.geometry=void 0!==a?a:new E;this.material=void 0!==b?b:new Fa({color:16777215*Math.random()})}function Ac(){z.call(this);this.type="Group"}function pd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0)}ba.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;m()}function Lb(a,b,
13951 c,d,e,f,g,h,k,m,q,v){ba.call(this,null,f,g,h,k,m,d,e,q,v);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function qd(a,b,c,d,e,f,g,h,k){ba.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Bc(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);ba.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,
13952 height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Mb(a){E.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f,g=[0,0],h={},k,m,q=["a","b","c"];if(a&&a.isGeometry){var v=a.faces;c=0;for(e=v.length;c<e;c++){var p=v[c];for(d=0;3>d;d++)k=p[q[d]],m=p[q[(d+1)%3]],g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]})}for(k in h)c=h[k],q=a.vertices[c.index1],b.push(q.x,q.y,q.z),q=a.vertices[c.index2],
13953 b.push(q.x,q.y,q.z)}else if(a&&a.isBufferGeometry){var r,q=new n;if(null!==a.index){v=a.attributes.position;p=a.index;r=a.groups;0===r.length&&(r=[{start:0,count:p.count,materialIndex:0}]);a=0;for(f=r.length;a<f;++a)for(c=r[a],d=c.start,e=c.count,c=d,e=d+e;c<e;c+=3)for(d=0;3>d;d++)k=p.getX(c+d),m=p.getX(c+(d+1)%3),g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]});for(k in h)c=h[k],q.fromBufferAttribute(v,c.index1),b.push(q.x,q.y,q.z),q.fromBufferAttribute(v,
13954 c.index2),b.push(q.x,q.y,q.z)}else for(v=a.attributes.position,c=0,e=v.count/3;c<e;c++)for(d=0;3>d;d++)h=3*c+d,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z),h=3*c+(d+1)%3,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z)}this.addAttribute("position",new B(b,3))}function Cc(a,b,c){J.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function Nb(a,b,c){E.call(this);this.type="ParametricBufferGeometry";this.parameters=
13955 {func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new n,k=new n,m=new n,q=new n,v=new n,p,r,l=b+1;for(p=0;p<=c;p++){var t=p/c;for(r=0;r<=b;r++){var y=r/b,k=a(y,t,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(m=a(y-1E-5,t,m),q.subVectors(k,m)):(m=a(y+1E-5,t,m),q.subVectors(m,k));0<=t-1E-5?(m=a(y,t-1E-5,m),v.subVectors(k,m)):(m=a(y,t+1E-5,m),v.subVectors(m,k));h.crossVectors(q,v).normalize();f.push(h.x,h.y,h.z);g.push(y,t)}}for(p=0;p<c;p++)for(r=0;r<b;r++)a=p*l+r+1,h=(p+1)*l+r+1,k=(p+1)*l+r,d.push(p*l+r,a,k),
13956 d.push(a,h,k);this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("normal",new B(f,3));this.addAttribute("uv",new B(g,2))}function Dc(a,b,c,d){J.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new za(a,b,c,d));this.mergeVertices()}function za(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){var d=3*b;c.x=a[d+0];c.y=a[d+1];c.z=a[d+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===
13957 c.z&&(k[b]=d/2/Math.PI+.5)}E.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new n,d=new n,g=new n,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k=c,l=d,y=g,x=Math.pow(2,a),u=[],H,w;for(H=0;H<=x;H++){u[H]=[];var I=k.clone().lerp(y,H/x),W=l.clone().lerp(y,H/x),D=x-H;for(w=0;w<=D;w++)u[H][w]=0===w&&H===x?I:I.clone().lerp(W,w/D)}for(H=0;H<x;H++)for(w=0;w<2*(x-H)-1;w++)k=Math.floor(w/
13958 2),0===w%2?(e(u[H][k+1]),e(u[H+1][k]),e(u[H][k])):(e(u[H][k+1]),e(u[H+1][k+1]),e(u[H+1][k]))}})(d);(function(a){for(var b=new n,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new n,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=new n,b=new n,c=new n,d=new n,e=new C,f=new C,l=new C,y=0,
13959 x=0;y<h.length;y+=9,x+=6){a.set(h[y+0],h[y+1],h[y+2]);b.set(h[y+3],h[y+4],h[y+5]);c.set(h[y+6],h[y+7],h[y+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);l.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var u=Math.atan2(d.z,-d.x);g(e,x+0,a,u);g(f,x+2,b,u);g(l,x+4,c,u)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new B(h,3));this.addAttribute("normal",
13960 new B(h.slice(),3));this.addAttribute("uv",new B(k,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Ec(a,b){J.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Ob(a,b){za.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Fc(a,b){J.call(this);this.type="OctahedronGeometry";this.parameters=
13961 {radius:a,detail:b};this.fromBufferGeometry(new lb(a,b));this.mergeVertices()}function lb(a,b){za.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Gc(a,b){J.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2;za.call(this,[-1,c,0,1,c,0,
13962 -1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Hc(a,b){J.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;za.call(this,
13963 [-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ic(a,
13964 b,c,d,e,f){J.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Rb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Rb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(v=0;v<=d;v++){var q=v/d*Math.PI*2,l=Math.sin(q),q=-Math.cos(q);
13965 k.x=q*m.x+l*e.x;k.y=q*m.y+l*e.y;k.z=q*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;p.push(h.x,h.y,h.z)}}E.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new n,k=new n,m=new C,q,v,p=[],r=[],l=[],t=[];for(q=0;q<b;q++)f(q);f(!1===e?b:0);for(q=0;q<=
13966 b;q++)for(v=0;v<=d;v++)m.x=q/b,m.y=v/d,l.push(m.x,m.y);(function(){for(v=1;v<=b;v++)for(q=1;q<=d;q++){var a=(d+1)*v+(q-1),c=(d+1)*v+q,e=(d+1)*(v-1)+q;t.push((d+1)*(v-1)+(q-1),a,e);t.push(a,c,e)}})();this.setIndex(t);this.addAttribute("position",new B(p,3));this.addAttribute("normal",new B(r,3));this.addAttribute("uv",new B(l,2))}function Jc(a,b,c,d,e,f,g){J.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");
13967 this.fromBufferGeometry(new Sb(a,b,c,d,e,f));this.mergeVertices()}function Sb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}E.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],m=[],q=[],v,p,r=new n,l=new n,t=new n,y=new n,x=new n,u=new n,H=new n;for(v=
13968 0;v<=c;++v)for(p=v/c*e*Math.PI*2,g(p,e,f,a,t),g(p+.01,e,f,a,y),u.subVectors(y,t),H.addVectors(y,t),x.crossVectors(u,H),H.crossVectors(x,u),x.normalize(),H.normalize(),p=0;p<=d;++p){var w=p/d*Math.PI*2,I=-b*Math.cos(w),w=b*Math.sin(w);r.x=t.x+(I*H.x+w*x.x);r.y=t.y+(I*H.y+w*x.y);r.z=t.z+(I*H.z+w*x.z);k.push(r.x,r.y,r.z);l.subVectors(r,t).normalize();m.push(l.x,l.y,l.z);q.push(v/c);q.push(p/d)}for(p=1;p<=c;p++)for(v=1;v<=d;v++)a=(d+1)*p+(v-1),b=(d+1)*p+v,e=(d+1)*(p-1)+v,h.push((d+1)*(p-1)+(v-1),a,e),
13969 h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new B(k,3));this.addAttribute("normal",new B(m,3));this.addAttribute("uv",new B(q,2))}function Kc(a,b,c,d,e){J.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Tb(a,b,c,d,e));this.mergeVertices()}function Tb(a,b,c,d,e){E.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=
13970 b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new n,q=new n,v=new n,p,r;for(p=0;p<=c;p++)for(r=0;r<=d;r++){var l=r/d*e,t=p/c*Math.PI*2;q.x=(a+b*Math.cos(t))*Math.cos(l);q.y=(a+b*Math.cos(t))*Math.sin(l);q.z=b*Math.sin(t);g.push(q.x,q.y,q.z);m.x=a*Math.cos(l);m.y=a*Math.sin(l);v.subVectors(q,m).normalize();h.push(v.x,v.y,v.z);k.push(r/d);k.push(p/c)}for(p=1;p<=c;p++)for(r=1;r<=d;r++)a=(d+1)*(p-1)+r-1,b=(d+1)*(p-1)+r,e=(d+1)*p+r,f.push((d+1)*p+r-1,a,e),f.push(a,
13971 b,e);this.setIndex(f);this.addAttribute("position",new B(g,3));this.addAttribute("normal",new B(h,3));this.addAttribute("uv",new B(k,2))}function cb(a,b){J.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Ga(a,b));this.mergeVertices()}function Ga(a,b){"undefined"!==typeof a&&(E.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Lc(a,b){J.call(this);this.type="TextGeometry";
13972 this.parameters={text:a,parameters:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){b=b||{};var c=b.font;if(!c||!c.isFont)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new J;c=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);Ga.call(this,c,b);this.type="TextBufferGeometry"}
13973 function Mc(a,b,c,d,e,f,g){J.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new mb(a,b,c,d,e,f,g));this.mergeVertices()}function mb(a,b,c,d,e,f,g){E.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==
13974 d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,m,q=0,v=[],p=new n,r=new n,l=[],t=[],y=[],x=[];for(m=0;m<=c;m++){var u=[],H=m/c;for(k=0;k<=b;k++){var w=k/b;p.x=-a*Math.cos(d+w*e)*Math.sin(f+H*g);p.y=a*Math.cos(f+H*g);p.z=a*Math.sin(d+w*e)*Math.sin(f+H*g);t.push(p.x,p.y,p.z);r.set(p.x,p.y,p.z).normalize();y.push(r.x,r.y,r.z);x.push(w,1-H);u.push(q++)}v.push(u)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=v[m][k+1],d=v[m][k],e=v[m+1][k],g=v[m+1][k+1],(0!==m||0<f)&&l.push(a,d,
13975 g),(m!==c-1||h<Math.PI)&&l.push(d,e,g);this.setIndex(l);this.addAttribute("position",new B(t,3));this.addAttribute("normal",new B(y,3));this.addAttribute("uv",new B(x,2))}function Nc(a,b,c,d,e,f){J.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Vb(a,b,c,d,e,f));this.mergeVertices()}function Vb(a,b,c,d,e,f){E.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,
13976 outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||20;b=b||50;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],m=[],q=a,v=(b-a)/d,p=new n,r=new C,l,t;for(l=0;l<=d;l++){for(t=0;t<=c;t++)a=e+t/c*f,p.x=q*Math.cos(a),p.y=q*Math.sin(a),h.push(p.x,p.y,p.z),k.push(0,0,1),r.x=(p.x/b+1)/2,r.y=(p.y/b+1)/2,m.push(r.x,r.y);q+=v}for(l=0;l<d;l++)for(b=l*(c+1),t=0;t<c;t++)a=t+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,
13977 f,q);this.setIndex(g);this.addAttribute("position",new B(h,3));this.addAttribute("normal",new B(k,3));this.addAttribute("uv",new B(m,2))}function Oc(a,b,c,d){J.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Wb(a,b,c,d));this.mergeVertices()}function Wb(a,b,c,d){E.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=Y.clamp(d,
13978 0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new n,m=new C,q,v;for(q=0;q<=b;q++){v=c+q*h*d;var p=Math.sin(v),r=Math.cos(v);for(v=0;v<=a.length-1;v++)k.x=a[v].x*p,k.y=a[v].y,k.z=a[v].x*r,f.push(k.x,k.y,k.z),m.x=q/b,m.y=v/(a.length-1),g.push(m.x,m.y)}for(q=0;q<b;q++)for(v=0;v<a.length-1;v++)c=v+q*a.length,h=c+a.length,k=c+a.length+1,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new B(f,3));this.addAttribute("uv",new B(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=
13979 this.attributes.normal.array,e=new n,f=new n,g=new n,c=b*a.length*3,v=q=0;q<a.length;q++,v+=3)e.x=d[v+0],e.y=d[v+1],e.z=d[v+2],f.x=d[c+v+0],f.y=d[c+v+1],f.z=d[c+v+2],g.addVectors(e,f).normalize(),d[v+0]=d[c+v+0]=g.x,d[v+1]=d[c+v+1]=g.y,d[v+2]=d[c+v+2]=g.z}function Xb(a,b){J.call(this);this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new Yb(a,
13980 b));this.mergeVertices()}function Yb(a,b){function c(a){var c,h,m=e.length/3;a=a.extractPoints(b);var l=a.shape,n=a.holes;if(!1===Ia.isClockWise(l))for(l=l.reverse(),a=0,c=n.length;a<c;a++)h=n[a],!0===Ia.isClockWise(h)&&(n[a]=h.reverse());var y=Ia.triangulateShape(l,n);a=0;for(c=n.length;a<c;a++)h=n[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],e.push(h.x,h.y,0),f.push(0,0,1),g.push(h.x,h.y);a=0;for(c=y.length;a<c;a++)l=y[a],d.push(l[0]+m,l[1]+m,l[2]+m),k+=3}E.call(this);this.type="ShapeBufferGeometry";
13981 this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("normal",new B(f,3));this.addAttribute("uv",new B(g,2))}function Zb(a,b){E.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[],d=Math.cos(Y.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g,h,k=["a","b","c"],m;a.isBufferGeometry?
13982 (m=new J,m.fromBufferGeometry(a)):m=a.clone();m.mergeVertices();m.computeFaceNormals();var q=m.vertices;m=m.faces;for(var v=0,p=m.length;v<p;v++)for(var l=m[v],n=0;3>n;n++)g=l[k[n]],h=l[k[(n+1)%3]],e[0]=Math.min(g,h),e[1]=Math.max(g,h),g=e[0]+","+e[1],void 0===f[g]?f[g]={index1:e[0],index2:e[1],face1:v,face2:void 0}:f[g].face2=v;for(g in f)if(e=f[g],void 0===e.face2||m[e.face1].normal.dot(m[e.face2].normal)<=d)k=q[e.index1],c.push(k.x,k.y,k.z),k=q[e.index2],c.push(k.x,k.y,k.z);this.addAttribute("position",
13983 new B(c,3))}function nb(a,b,c,d,e,f,g,h){J.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Ua(a,b,c,d,e,f,g,h));this.mergeVertices()}function Ua(a,b,c,d,e,f,g,h){function k(c){var e,f,k,t=new C,D=new n,O=0,aa=!0===c?a:b,F=!0===c?1:-1;f=ca;for(e=1;e<=d;e++)v.push(0,y*F,0),p.push(0,F,0),l.push(.5,.5),ca++;k=ca;for(e=0;e<=d;e++){var B=e/d*h+g,z=Math.cos(B),
13984 B=Math.sin(B);D.x=aa*B;D.y=y*F;D.z=aa*z;v.push(D.x,D.y,D.z);p.push(0,F,0);t.x=.5*z+.5;t.y=.5*B*F+.5;l.push(t.x,t.y);ca++}for(e=0;e<d;e++)t=f+e,D=k+e,!0===c?q.push(D,D+1,t):q.push(D+1,D,t),O+=3;m.addGroup(x,O,!0===c?1:2);x+=O}E.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||
13985 1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],v=[],p=[],l=[],ca=0,t=[],y=c/2,x=0;(function(){var f,k,w=new n,I=new n,W=0,D=(b-a)/c;for(k=0;k<=e;k++){var O=[],aa=k/e,F=aa*(b-a)+a;for(f=0;f<=d;f++){var B=f/d,C=B*h+g,z=Math.sin(C),C=Math.cos(C);I.x=F*z;I.y=-aa*c+y;I.z=F*C;v.push(I.x,I.y,I.z);w.set(z,D,C).normalize();p.push(w.x,w.y,w.z);l.push(B,1-aa);O.push(ca++)}t.push(O)}for(f=0;f<d;f++)for(k=0;k<e;k++)w=t[k+1][f],I=t[k+1][f+1],D=t[k][f+1],q.push(t[k][f],w,D),q.push(w,I,D),
13986 W+=6;m.addGroup(x,W,0);x+=W})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new B(v,3));this.addAttribute("normal",new B(p,3));this.addAttribute("uv",new B(l,2))}function Pc(a,b,c,d,e,f,g){nb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Qc(a,b,c,d,e,f,g){Ua.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,
13987 height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Rc(a,b,c,d){J.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new $b(a,b,c,d));this.mergeVertices()}function $b(a,b,c,d){E.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||50;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=[],g=[],
13988 h=[],k,m,q=new n,v=new C;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);m=0;for(k=3;m<=b;m++,k+=3){var p=c+m/b*d;q.x=a*Math.cos(p);q.y=a*Math.sin(p);f.push(q.x,q.y,q.z);g.push(0,0,1);v.x=(f[k]/a+1)/2;v.y=(f[k+1]/a+1)/2;h.push(v.x,v.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new B(f,3));this.addAttribute("normal",new B(g,3));this.addAttribute("uv",new B(h,2))}function ac(a){ra.call(this,{uniforms:Ca.merge([R.lights,{opacity:{value:1}}]),vertexShader:X.shadow_vert,
13989 fragmentShader:X.shadow_frag});this.transparent=this.lights=!0;Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(a){this.uniforms.opacity.value=a}}});this.setValues(a)}function bc(a){ra.call(this,a);this.type="RawShaderMaterial"}function Pa(a){U.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new G(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=
13990 null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=
13991 !1;this.setValues(a)}function ob(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ja(a){U.call(this);this.type="MeshPhongMaterial";this.color=new G(16777215);this.specular=new G(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=
13992 1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function pb(a){Ja.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;
13993 this.setValues(a)}function qb(a){U.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function rb(a){U.call(this);this.type="MeshLambertMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=
13994 1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function sb(a){U.call(this);this.type="LineDashedMaterial";this.color=new G(16777215);this.scale=this.linewidth=1;this.dashSize=
13995 3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Zd(a,b,c){var d=this,e=!1,f=0,g=0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)}}function Ka(a){this.manager=void 0!==a?a:va}function Oe(a){this.manager=void 0!==
13996 a?a:va;this._parser=null}function $d(a){this.manager=void 0!==a?a:va;this._parser=null}function Sc(a){this.manager=void 0!==a?a:va}function ae(a){this.manager=void 0!==a?a:va}function rd(a){this.manager=void 0!==a?a:va}function na(a,b){z.call(this);this.type="Light";this.color=new G(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function sd(a,b,c){na.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(z.DefaultUp);this.updateMatrix();this.groundColor=new G(b)}
13997 function tb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new K}function td(){tb.call(this,new qa(50,1,.5,500))}function ud(a,b,c,d,e,f){na.call(this,a,b);this.type="SpotLight";this.position.copy(z.DefaultUp);this.updateMatrix();this.target=new z;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=
13998 void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new td}function vd(a,b,c,d){na.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new tb(new qa(90,1,.5,500))}function wd(){tb.call(this,new Fb(-5,5,5,-5,.5,500))}function xd(a,b){na.call(this,a,b);this.type="DirectionalLight";this.position.copy(z.DefaultUp);this.updateMatrix();
13999 this.target=new z;this.shadow=new wd}function yd(a,b){na.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function zd(a,b,c,d){na.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function wa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Ad(a,b,c,d){wa.call(this,a,b,c,d);this._offsetNext=
14000 this._weightNext=this._offsetPrev=this._weightPrev=-0}function Tc(a,b,c,d){wa.call(this,a,b,c,d)}function Bd(a,b,c,d){wa.call(this,a,b,c,d)}function ub(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=ia.convertArray(b,this.TimeBufferType);this.values=ia.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function cc(a,b,
14001 c,d){ub.call(this,a,b,c,d)}function Cd(a,b,c,d){wa.call(this,a,b,c,d)}function Uc(a,b,c,d){ub.call(this,a,b,c,d)}function dc(a,b,c,d){ub.call(this,a,b,c,d)}function Dd(a,b,c,d){ub.call(this,a,b,c,d)}function Ed(a,b,c){ub.call(this,a,b,c)}function Fd(a,b,c,d){ub.call(this,a,b,c,d)}function vb(a,b,c,d){ub.apply(this,arguments)}function Da(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=Y.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Gd(a){this.manager=
14002 void 0!==a?a:va;this.textures={}}function be(a){this.manager=void 0!==a?a:va}function ec(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function ce(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:va;this.withCredentials=!1}function Pe(a){this.manager=void 0!==a?a:va;this.texturePath=""}function Qe(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*
14003 c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function wb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function xb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function ua(){this.arcLengthDivisions=200}function Qa(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Vc(){this.arcLengthDivisions=200;this.curves=[];this.autoClose=!1}function Va(a,b,c,d,e,f,g,h){this.arcLengthDivisions=200;this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=
14004 f;this.aClockwise=g;this.aRotation=h||0}function yb(a){this.arcLengthDivisions=200;this.points=void 0===a?[]:a}function fc(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c;this.v3=d}function gc(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function Wc(a){Vc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function zb(){Wc.apply(this,arguments);this.holes=[]}function de(){this.subPaths=[];this.currentPath=null}function ee(a){this.data=a}function Re(a){this.manager=
14005 void 0!==a?a:va}function fe(a){this.manager=void 0!==a?a:va}function Se(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new qa;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new qa;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function Hd(a,b,c){z.call(this);this.type="CubeCamera";var d=new qa(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new n(1,0,0));this.add(d);var e=new qa(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new n(-1,0,0));this.add(e);
14006 var f=new qa(90,1,a,b);f.up.set(0,0,1);f.lookAt(new n(0,1,0));this.add(f);var g=new qa(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new n(0,-1,0));this.add(g);var h=new qa(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new n(0,0,1));this.add(h);var k=new qa(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new n(0,0,-1));this.add(k);this.renderTarget=new Db(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=
14007 this.renderTarget,p=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=p;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function ge(){z.call(this);this.type="AudioListener";this.context=he.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=
14008 null}function hc(a){z.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function ie(a){hc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function je(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==
14009 b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function ke(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Te(a,b,c){c=c||ha.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function ha(a,
14010 b,c){this.path=b;this.parsedPath=c||ha.parseTrackName(b);this.node=ha.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Ue(a){this.uuid=Y.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-
14011 e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function Ve(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=
14012 null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function We(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Id(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function le(){E.call(this);this.type="InstancedBufferGeometry";
14013 this.maxInstancedCount=void 0}function me(a,b,c,d){this.uuid=Y.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function ic(a,b){this.uuid=Y.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function ne(a,b,c){ic.call(this,a,b);this.meshPerAttribute=c||1}function oe(a,b,c){Z.call(this,a,b);this.meshPerAttribute=c||1}function Xe(a,b,c,d){this.ray=
14014 new kb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function Ye(a,b){return a.distance-b.distance}function pe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)pe(a[d],b,c,!0)}}function Ze(a){this.autoStart=void 0!==a?
14015 a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function $e(a,b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function af(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function ta(a,b){la.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function Xc(a){z.call(this);
14016 this.material=a;this.render=function(a){}}function Yc(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new E;b=new B(6*b,3);c.addAttribute("position",b);Q.call(this,c,new ea({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function jc(a){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=
14017 !1;a=new E;for(var b=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1],c=0,d=1;32>c;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new B(b,3));b=new ea({fog:!1});this.cone=new Q(a,b);this.add(this.cone);this.update()}function bf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,bf(a.children[c]));return b}function kc(a){for(var b=bf(a),c=new E,d=[],e=[],f=new G(0,
14018 0,1),g=new G(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new B(d,3));c.addAttribute("color",new B(e,3));d=new ea({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});Q.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.onBeforeRender()}function lc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new mb(b,4,2),d=new ya({wireframe:!0,
14019 fog:!1});d.color.copy(this.light.color);la.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1}function mc(a){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new ea({color:a.color});var b=new E;b.addAttribute("position",new Z(new Float32Array(15),3));this.add(new sa(b,a));this.update()}function nc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=
14020 new lb(b);c.rotateY(.5*Math.PI);var d=new ya({vertexColors:2,wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);c.addAttribute("color",new Z(e,3));this.add(new la(c,d));this.update()}function Zc(a,b,c,d){a=a||10;b=b||10;c=new G(void 0!==c?c:4473924);d=new G(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,m=0,q=-g;k<=b;k++,q+=f){a.push(-g,0,q,g,0,q);a.push(q,0,-g,q,0,g);var l=k===e?c:d;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,
14021 m);m+=3}b=new E;b.addAttribute("position",new B(a,3));b.addAttribute("color",new B(h,3));c=new ea({vertexColors:2});Q.call(this,b,c)}function Jd(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new G(void 0!==e?e:4473924);f=new G(void 0!==f?f:8947848);var g=[],h=[],k,m,q,l,p;for(q=0;q<=b;q++)m=q/b*2*Math.PI,k=Math.sin(m)*a,m=Math.cos(m)*a,g.push(0,0,0),g.push(k,0,m),p=q&1?e:f,h.push(p.r,p.g,p.b),h.push(p.r,p.g,p.b);for(q=0;q<=c;q++)for(p=q&1?e:f,l=a-a/c*q,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*l,
14022 m=Math.cos(m)*l,g.push(k,0,m),h.push(p.r,p.g,p.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(p.r,p.g,p.b);a=new E;a.addAttribute("position",new B(g,3));a.addAttribute("color",new B(h,3));g=new ea({vertexColors:2});Q.call(this,a,g)}function $c(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");
14023 c=new E;b=new B(6*b,3);c.addAttribute("position",b);Q.call(this,c,new ea({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function oc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new E;c.addAttribute("position",new B([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ea({fog:!1});this.add(new sa(c,d));c=new E;c.addAttribute("position",new B([0,0,0,0,0,1],3));this.add(new sa(c,d));this.update()}
14024 function ad(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new E,e=new ea({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new G(16755200),m=new G(16711680),q=new G(43775),l=new G(16777215),p=new G(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p",
14025 "n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",l);b("p","c",p);b("cn1","cn2",p);b("cn3","cn4",p);b("cf1","cf2",p);b("cf3","cf4",p);d.addAttribute("position",new B(f,3));d.addAttribute("color",new B(g,3));Q.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Ab(a,b){this.object=a;void 0===b&&(b=16776960);var c=new Uint16Array([0,
14026 1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),d=new Float32Array(24),e=new E;e.setIndex(new Z(c,1));e.addAttribute("position",new Z(d,3));Q.call(this,e,new ea({color:b}));this.matrixAutoUpdate=!1;this.update()}function Bb(a,b,c,d,e,f){z.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Kd&&(Kd=new E,Kd.addAttribute("position",new B([0,0,0,0,1,0],3)),qe=new Ua(0,.5,1,5,1),qe.translate(0,-.5,0));this.position.copy(b);this.line=new sa(Kd,new ea({color:d}));
14027 this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new la(qe,new ya({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function Ld(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new E;a.addAttribute("position",new B(b,3));a.addAttribute("color",new B([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ea({vertexColors:2});Q.call(this,a,b)}function re(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*
14028 (h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,m,q){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+q)+(h-g)/q)*m;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function La(a){this.arcLengthDivisions=200;2>a.length&&console.warn("THREE.CatmullRomCurve3: Points array needs at least two entries.");this.points=a||[];this.closed=!1}function bd(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=
14029 c;this.v3=d}function cd(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function dd(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Md(a,b,c,d,e,f){Va.call(this,a,b,c,c,d,e,f)}function cf(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type="catmullrom";this.closed=!0}function df(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type=
14030 "catmullrom"}function se(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});
14031 void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(xa.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},
14032 hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,1)}}},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;for(var b=b.slice(0),c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var Y={DEG2RAD:Math.PI/180,RAD2DEG:180/
14033 Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,
14034 b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*Y.DEG2RAD},radToDeg:function(a){return a*Y.RAD2DEG},isPowerOfTwo:function(a){return 0===
14035 (a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=
14036 a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
14037 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},
14038 subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,
14039 Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);
14040 this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||
14041 1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,
14042 a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-
14043 a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}});var hf=0;ba.DEFAULT_IMAGE=void 0;ba.DEFAULT_MAPPING=300;Object.defineProperty(ba.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ba.prototype,xa.prototype,{constructor:ba,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=
14044 a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,
14045 name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=Y.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),g.width=c.width,g.height=
14046 c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%
14047 2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(fa.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},
14048 setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,
14049 this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,
14050 b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=
14051 a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/
14052 b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781):
14053 (c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,
14054 a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new fa,b=new fa);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,
14055 c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):
14056 Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+
14057 Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===
14058 b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Cb.prototype,xa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==
14059 a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Db.prototype=Object.create(Cb.prototype);
14060 Db.prototype.constructor=Db;Db.prototype.isWebGLRenderTargetCube=!0;Object.assign(oa,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||m!==l){f=1-g;var p=h*d+k*q+m*l+c*e,r=0<=p?1:-1,n=1-p*p;n>Number.EPSILON&&(n=Math.sqrt(n),p=Math.atan2(n,p*r),f=Math.sin(f*p)/n,g=Math.sin(g*p)/n);r*=g;h=h*f+d*r;k=k*f+q*r;m=m*f+l*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*
14061 m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(oa.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(oa.prototype,{set:function(a,b,c,d){this._x=
14062 a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z,f=a.order,g=Math.cos,h=Math.sin,k=g(c/2),m=g(d/2),g=g(e/2),c=h(c/2),d=
14063 h(d/2),e=h(e/2);"XYZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"YXZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"ZXY"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"ZYX"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"YZX"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g-c*d*e):"XZY"===f&&(this._x=c*m*g-
14064 k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0<m?(c=.5/Math.sqrt(m+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+
14065 c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new n,b;return function(c,d){void 0===a&&(a=new n);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=
14066 a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();
14067 0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,
14068 k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),
14069 this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,
14070 b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(n.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=
14071 b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
14072 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;
14073 return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*
14074 b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new oa;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new oa;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*
14075 b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*
14076 -g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},
14077 divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},
14078 clampScalar:function(){var a=new n,b=new n;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);
14079 this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*
14080 this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),
14081 this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new n;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new n;return function(b){return this.sub(a.copy(b).multiplyScalar(2*
14082 this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(Y.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*
14083 a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,
14084 4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(K.prototype,
14085 {isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,q,l,p,r,n,t){var y=this.elements;y[0]=a;y[4]=b;y[8]=c;y[12]=d;y[1]=e;y[5]=f;y[9]=g;y[13]=h;y[2]=k;y[6]=m;y[10]=q;y[14]=l;y[3]=p;y[7]=r;y[11]=n;y[15]=t;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];
14086 b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new n;return function(b){var c=this.elements,d=b.elements,
14087 e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),
14088 h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,q=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-q*d;b[9]=-c*g;b[2]=q-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a+q*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=q+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a-q*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=q-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,q=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*
14089 d+q,b[1]=g*e,b[5]=q*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=q-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-q*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+q,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=q*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a=
14090 c*g;var m=c*h,c=c*k,q=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(q+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+q);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new n,b=new n,c=new n;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,
14091 a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],q=c[5],l=c[9],
14092 p=c[13],r=c[2],n=c[6],t=c[10],y=c[14],x=c[3],u=c[7],H=c[11],c=c[15],w=d[0],I=d[4],W=d[8],D=d[12],O=d[1],B=d[5],F=d[9],C=d[13],z=d[2],E=d[6],G=d[10],K=d[14],P=d[3],M=d[7],V=d[11],d=d[15];e[0]=f*w+g*O+h*z+k*P;e[4]=f*I+g*B+h*E+k*M;e[8]=f*W+g*F+h*G+k*V;e[12]=f*D+g*C+h*K+k*d;e[1]=m*w+q*O+l*z+p*P;e[5]=m*I+q*B+l*E+p*M;e[9]=m*W+q*F+l*G+p*V;e[13]=m*D+q*C+l*K+p*d;e[2]=r*w+n*O+t*z+y*P;e[6]=r*I+n*B+t*E+y*M;e[10]=r*W+n*F+t*G+y*V;e[14]=r*D+n*C+t*K+y*d;e[3]=x*w+u*O+H*z+c*P;e[7]=x*I+u*B+H*E+c*M;e[11]=x*W+u*F+H*G+
14093 c*V;e[15]=x*D+u*C+H*K+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new n;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=
14094 a[1],g=a[5],h=a[9],k=a[13],m=a[2],q=a[6],l=a[10],p=a[14];return a[3]*(+e*h*q-d*k*q-e*g*l+c*k*l+d*g*p-c*h*p)+a[7]*(+b*h*p-b*k*l+e*f*l-d*f*p+d*k*m-e*h*m)+a[11]*(+b*k*q-b*g*p-e*f*q+c*f*p+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*q+b*g*l+d*f*q-c*f*l+c*h*m)},transpose:function(){var a=this.elements,b;b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=this.elements;b[12]=
14095 a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[1],g=d[2],h=d[3],k=d[4],m=d[5],q=d[6],l=d[7],p=d[8],r=d[9],n=d[10],t=d[11],y=d[12],x=d[13],u=d[14],d=d[15],H=r*u*l-x*n*l+x*q*t-m*u*t-r*q*d+m*n*d,w=y*n*l-p*u*l-y*q*t+k*u*t+p*q*d-k*n*d,I=p*x*l-y*r*l+y*m*t-k*x*t-p*m*d+k*r*d,W=y*r*q-p*x*q-y*m*n+k*x*n+p*m*u-k*r*u,D=e*H+f*w+g*I+h*W;if(0===D){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");
14096 return this.identity()}D=1/D;c[0]=H*D;c[1]=(x*n*h-r*u*h-x*g*t+f*u*t+r*g*d-f*n*d)*D;c[2]=(m*u*h-x*q*h+x*g*l-f*u*l-m*g*d+f*q*d)*D;c[3]=(r*q*h-m*n*h-r*g*l+f*n*l+m*g*t-f*q*t)*D;c[4]=w*D;c[5]=(p*u*h-y*n*h+y*g*t-e*u*t-p*g*d+e*n*d)*D;c[6]=(y*q*h-k*u*h-y*g*l+e*u*l+k*g*d-e*q*d)*D;c[7]=(k*n*h-p*q*h+p*g*l-e*n*l-k*g*t+e*q*t)*D;c[8]=I*D;c[9]=(y*r*h-p*x*h-y*f*t+e*x*t+p*f*d-e*r*d)*D;c[10]=(k*x*h-y*m*h+y*f*l-e*x*l-k*f*d+e*m*d)*D;c[11]=(p*m*h-k*r*h-p*f*l+e*r*l+k*f*t-e*m*t)*D;c[12]=W*D;c[13]=(p*x*g-y*r*g+y*f*n-e*x*
14097 n-p*f*u+e*r*u)*D;c[14]=(y*m*g-k*x*g-y*f*q+e*x*q+k*f*u-e*m*u)*D;c[15]=(k*r*g-p*m*g+p*f*q-e*r*q-k*f*n+e*m*n)*D;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,
14098 0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*
14099 g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new n,b=new K;return function(c,d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),
14100 k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;var f=1/h,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");
14101 var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;
14102 a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});db.prototype=Object.create(ba.prototype);
14103 db.prototype.constructor=db;db.prototype.isDataTexture=!0;Xa.prototype=Object.create(ba.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Ce=new ba,De=new Xa,xe=[],ze=[],Be=new Float32Array(16),Ae=new Float32Array(9);He.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Pd=/([\w\d_]+)(\])?(\[|\.)?/g;
14104 eb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};eb.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};eb.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};eb.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var lg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,
14105 beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,
14106 darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,
14107 khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,
14108 mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,
14109 peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,
14110 yellow:16776960,yellowgreen:10145074};Object.assign(G.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1<d&&
14111 --d;return d<1/6?a+6*(c-a)*d:.5>d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=Y.euclideanModulo(b,1);c=Y.clamp(c,0,1);d=Y.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=
14112 /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=
14113 parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&
14114 (c=lg[a],void 0!==c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);var c=0<b?1/b:1;this.r=Math.pow(a.r,c);this.g=Math.pow(a.g,c);this.b=Math.pow(a.b,c);return this},
14115 convertGammaToLinear:function(){var a=this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===
14116 e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},
14117 addScalar:function(a){this.r+=a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,
14118 b){void 0===b&&(b=0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}});var R={common:{diffuse:{value:new G(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new fa(0,0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},
14119 aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new C(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},
14120 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:[]},
14121 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new G(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new fa(0,0,1,1)}}},Ca={merge:function(a){for(var b=
14122 {},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},X={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",
14123 alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",
14124 aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",
14125 bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n",
14126 clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n",
14127 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",
14128 color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n",
14129 cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1  (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale =  bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n",
14130 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",
14131 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",
14132 envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n",
14133 envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n",
14134 envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n",
14135 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",
14136 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",
14137 lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",
14138 lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight  ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n",
14139 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",
14140 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",
14141 lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3(   1,   0, t.y ),\n\t\t\tvec3(   0, t.z,   0 ),\n\t\t\tvec3( t.w,   0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material )   GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n",
14142 lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
14143 logdepthbuf_fragment:"#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n",
14144 map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n",
14145 metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",
14146 morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n",
14147 normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
14148 normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n",
14149 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",
14150 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",
14151 roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
14152 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",
14153 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",
14154 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
14155 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",
14156 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",
14157 specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n  gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",
14158 uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n",
14159 uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",
14160 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
14161 cube_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
14162 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",
14163 distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n",
14164 equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
14165 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",
14166 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",
14167 meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
14168 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",
14169 meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
14170 meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
14171 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
14172 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",
14173 meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
14174 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",
14175 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
14176 normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
14177 points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
14178 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
14179 shadow_frag:"uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n"},$a={basic:{uniforms:Ca.merge([R.common,
14180 R.aomap,R.lightmap,R.fog]),vertexShader:X.meshbasic_vert,fragmentShader:X.meshbasic_frag},lambert:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.fog,R.lights,{emissive:{value:new G(0)}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.gradientmap,R.fog,R.lights,{emissive:{value:new G(0)},specular:{value:new G(1118481)},shininess:{value:30}}]),vertexShader:X.meshphong_vert,
14181 fragmentShader:X.meshphong_frag},standard:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.roughnessmap,R.metalnessmap,R.fog,R.lights,{emissive:{value:new G(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},points:{uniforms:Ca.merge([R.points,R.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:Ca.merge([R.common,R.fog,{scale:{value:1},
14182 dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,fragmentShader:X.linedashed_frag},depth:{uniforms:Ca.merge([R.common,R.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:Ca.merge([R.common,R.bumpmap,R.normalmap,R.displacementmap,{opacity:{value:1}}]),vertexShader:X.normal_vert,fragmentShader:X.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null},
14183 tFlip:{value:-1}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new n}},vertexShader:X.distanceRGBA_vert,fragmentShader:X.distanceRGBA_frag}};$a.physical={uniforms:Ca.merge([$a.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};Object.assign(fd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();
14184 for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||
14185 this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<
14186 this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},
14187 distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});var Jf=0;Object.assign(U.prototype,xa.prototype,{isMaterial:!0,onBeforeCompile:function(){},
14188 setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});
14189 var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);
14190 void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&
14191 (d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&
14192 (d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==
14193 this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&
14194 (d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);d.skinning=this.skinning;d.morphTargets=this.morphTargets;d.dithering=this.dithering;c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;this.lights=
14195 a.lights;this.blending=a.blending;this.side=a.side;this.shading=a.shading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=a.precision;this.polygonOffset=
14196 a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.dithering=a.dithering;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});
14197 ra.prototype=Object.create(U.prototype);ra.prototype.constructor=ra;ra.prototype.isShaderMaterial=!0;ra.prototype.copy=function(a){U.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Ca.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=
14198 a.extensions;return this};ra.prototype.toJSON=function(a){a=U.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Za.prototype=Object.create(U.prototype);Za.prototype.constructor=Za;Za.prototype.isMeshDepthMaterial=!0;Za.prototype.copy=function(a){U.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=
14199 a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Object.assign(Ra.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var m=a[h],q=a[h+1],l=a[h+2];m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);
14200 l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),q=a.getY(h),l=a.getZ(h);m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=
14201 new n;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<
14202 this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new n;return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new n;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){var a=
14203 new n;return function(b){var c=this;b.updateMatrixWorld(!0);b.traverse(function(b){var e,f;e=b.geometry;if(void 0!==e)if(e.isGeometry){var g=e.vertices;e=0;for(f=g.length;e<f;e++)a.copy(g[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}else if(e.isBufferGeometry&&(g=e.attributes.position,void 0!==g))for(e=0,f=g.count;e<f;e++)a.fromBufferAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(a)});return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||
14204 a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new n).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<
14205 this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new n;return function(b){this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0<a.normal.x?(b=a.normal.x*this.min.x,c=a.normal.x*this.max.x):(b=a.normal.x*this.max.x,c=a.normal.x*this.min.x);0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*
14206 this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,b){return(b||new n).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new n;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new n;return function(b){b=b||new Ea;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);
14207 this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new n,new n,new n,new n,new n,new n,new n,new n];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,
14208 this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Ea.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=
14209 new Ra;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,d.distanceToSquared(b[f]));this.radius=Math.sqrt(e);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-
14210 this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new n;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=
14211 a||new Ra;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Ba.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,
14212 0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new n;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),
14213 a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[3],h=c[6],k=c[1],m=c[4],q=c[7],l=c[2],p=c[5],c=c[8],r=d[0],n=d[3],t=d[6],y=d[1],x=d[4],u=d[7],H=d[2],w=d[5],d=d[8];e[0]=f*r+g*y+h*H;e[3]=f*n+g*x+h*w;e[6]=f*t+g*u+h*d;e[1]=k*r+m*y+q*H;e[4]=k*n+m*x+q*w;e[7]=k*t+m*u+q*d;e[2]=l*r+p*y+c*H;
14214 e[5]=l*n+p*x+c*w;e[8]=l*t+p*u+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3.getInverse no longer takes a Matrix4 argument.");var c=a.elements,d=this.elements,e=c[0],f=c[1],g=c[2],
14215 h=c[3],k=c[4],m=c[5],q=c[6],l=c[7],c=c[8],p=c*k-m*l,r=m*q-c*h,n=l*h-k*q,t=e*p+f*r+g*n;if(0===t){if(!0===b)throw Error("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");return this.identity()}t=1/t;d[0]=p*t;d[1]=(g*l-c*f)*t;d[2]=(m*f-g*k)*t;d[3]=r*t;d[4]=(c*e-g*q)*t;d[5]=(g*h-m*e)*t;d[6]=n*t;d[7]=(f*q-l*e)*t;d[8]=(k*e-f*h)*t;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=
14216 a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},
14217 toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});Object.assign(Aa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=
14218 new n,b=new n;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+
14219 this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new n).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new n;return function(b,c){var d=c||new n,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/
14220 f,0>f||1<f?void 0:d.copy(e).multiplyScalar(f).add(b.start)}}(),intersectsLine:function(a){var b=this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new n).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new n,b=new Ba;return function(c,d){var e=this.coplanarPoint(a).applyMatrix4(c),
14221 f=d||b.getNormalMatrix(c),f=this.normal.applyMatrix3(f).normalize();this.constant=-e.dot(f);return this}}(),translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(gd.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=
14222 this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],q=c[8],l=c[9],p=c[10],r=c[11],n=c[12],t=c[13],y=c[14],c=c[15];b[0].setComponents(f-a,m-g,r-q,c-n).normalize();b[1].setComponents(f+a,m+g,r+q,c+n).normalize();b[2].setComponents(f+d,m+h,r+l,c+t).normalize();b[3].setComponents(f-d,m-h,r-l,c-t).normalize();b[4].setComponents(f-e,m-k,r-p,c-y).normalize();b[5].setComponents(f+e,
14223 m+k,r+p,c+y).normalize();return this},intersectsObject:function(){var a=new Ea;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Ea;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=
14224 0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new n,b=new n;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>
14225 c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});ab.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");ab.DefaultOrder="XYZ";Object.defineProperties(ab.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;
14226 this.onChangeCallback()}}});Object.assign(ab.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=Y.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],q=e[2],l=e[6],
14227 e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(l,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(l,-1,1)),.99999>Math.abs(l)?(this._y=Math.atan2(-q,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(q,
14228 -1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(l,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-q,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(l,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=
14229 b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new oa;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=
14230 a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new n(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Qd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=
14231 this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!==(this.mask&a.mask)}});var Lf=0;z.DefaultUp=new n(0,1,0);z.DefaultMatrixAutoUpdate=!0;Object.assign(z.prototype,xa.prototype,{isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){this.quaternion.premultiply(a);
14232 return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new oa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new n(1,0,0);return function(b){return this.rotateOnAxis(a,
14233 b)}}(),rotateY:function(){var a=new n(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new n(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new n;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new n(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new n(0,1,0);return function(b){return this.translateOnAxis(a,
14234 b)}}(),translateZ:function(){var a=new n(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new K;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new K;return function(b){this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),add:function(a){if(1<arguments.length){for(var b=
14235 0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a);return this},remove:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);return this}b=this.children.indexOf(a);
14236 -1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1));return this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new n;this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},
14237 getWorldQuaternion:function(){var a=new n,b=new n;return function(c){c=c||new oa;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new oa;return function(b){b=b||new ab;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new n,b=new oa;return function(c){c=c||new n;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new oa;
14238 return function(b){b=b||new n;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,
14239 this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a));return c.uuid}function c(a){var b=[],
14240 c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||""===a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};f.uuid=this.uuid;f.type=this.type;""!==this.name&&(f.name=this.name);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);f.matrix=this.matrix.toArray();
14241 void 0!==this.geometry&&(f.geometry=b(a.geometries,this.geometry));if(void 0!==this.material)if(Array.isArray(this.material)){for(var g=[],h=0,k=this.material.length;h<k;h++)g.push(b(a.materials,this.material[h]));f.material=g}else f.material=b(a.materials,this.material);if(0<this.children.length)for(f.children=[],h=0;h<this.children.length;h++)f.children.push(this.children[h].toJSON(a).object);d&&(d=c(a.geometries),g=c(a.materials),h=c(a.textures),k=c(a.images),0<d.length&&(e.geometries=d),0<g.length&&
14242 (e.materials=g),0<h.length&&(e.textures=h),0<k.length&&(e.images=k));e.object=f;return e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;this.layers.mask=a.layers.mask;
14243 this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(var c=0;c<a.children.length;c++)this.add(a.children[c].clone());return this}});Na.prototype=Object.assign(Object.create(z.prototype),{constructor:Na,isCamera:!0,copy:function(a,b){z.prototype.copy.call(this,a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);
14244 return this},getWorldDirection:function(){var a=new oa;return function(b){b=b||new n;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){z.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});Fb.prototype=Object.assign(Object.create(Na.prototype),{constructor:Fb,isOrthographicCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);this.left=a.left;
14245 this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),
14246 c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=z.prototype.toJSON.call(this,
14247 a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});qa.prototype=Object.assign(Object.create(Na.prototype),{constructor:qa,isPerspectiveCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;this.view=
14248 null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*Y.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*Y.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*Y.RAD2DEG*Math.atan(Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},
14249 getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==f)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/
14250 g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=z.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});
14251 Object.assign(Sa.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});var Rd=0;Object.assign(J.prototype,xa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=
14252 (new Ba).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);
14253 this.applyMatrix(a);return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new z;return function(b){a.lookAt(b);
14254 a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[q[a].clone(),q[b].clone(),q[d].clone()]:[],r=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Sa(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([l[a].clone(),l[b].clone(),l[d].clone()]);void 0!==m&&c.faceVertexUvs[1].push([p[a].clone(),p[b].clone(),p[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
14255 g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var q=[],l=[],p=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new n(f[e],f[e+1],f[e+2])),void 0!==g&&q.push(new n(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new G(h[e],h[e+1],h[e+2])),void 0!==k&&l.push(new C(k[r],k[r+1])),void 0!==m&&p.push(new C(m[r],m[r+1]));var ca=a.groups;if(0<ca.length)for(e=0;e<
14256 ca.length;e++)for(var f=ca[e],t=f.start,y=f.count,r=t,t=t+y;r<t;r+=3)void 0!==d?b(d[r],d[r+1],d[r+2],f.materialIndex):b(r,r+1,r+2,f.materialIndex);else if(void 0!==d)for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();
14257 this.translate(a.x,a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new K;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new n,b=new n,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},
14258 computeVertexNormals:function(a){void 0===a&&(a=!0);var b,c,d;d=Array(this.vertices.length);b=0;for(c=this.vertices.length;b<c;b++)d[b]=new n;if(a){var e,f,g,h=new n,k=new n;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=this.vertices[c.a],f=this.vertices[c.b],g=this.vertices[c.c],h.subVectors(g,f),k.subVectors(e,f),h.cross(k),d[c.a].add(h),d[c.b].add(h),d[c.c].add(h)}else for(this.computeFaceNormals(),a=0,b=this.faces.length;a<b;a++)c=this.faces[a],d[c.a].add(c.normal),d[c.b].add(c.normal),
14259 d[c.c].add(c.normal);b=0;for(c=this.vertices.length;b<c;b++)d[b].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=c.vertexNormals,3===e.length?(e[0].copy(d[c.a]),e[1].copy(d[c.b]),e[2].copy(d[c.c])):(e[0]=d[c.a].clone(),e[1]=d[c.b].clone(),e[2]=d[c.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;this.computeFaceNormals();a=0;for(b=this.faces.length;a<b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),
14260 d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b,c,d,e;c=0;for(d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):
14261 e.__originalVertexNormals[a]=e.vertexNormals[a].clone();var f=new J;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={};this.morphNormals[a].faceNormals=[];this.morphNormals[a].vertexNormals=[];e=this.morphNormals[a].faceNormals;var g=this.morphNormals[a].vertexNormals,h,k;c=0;for(d=this.faces.length;c<d;c++)h=new n,k={a:new n,b:new n,c:new n},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();
14262 f.computeVertexNormals();c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(e.normal),k.a.copy(e.vertexNormals[0]),k.b.copy(e.vertexNormals[1]),k.c.copy(e.vertexNormals[2])}c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===
14263 this.boundingBox&&(this.boundingBox=new Ra);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Ea);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(a&&a.isGeometry){var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,m=this.faceVertexUvs[0],q=a.faceVertexUvs[0],l=this.colors,p=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new Ba).getNormalMatrix(b));a=0;for(var r=g.length;a<
14264 r;a++){var n=g[a].clone();void 0!==b&&n.applyMatrix4(b);f.push(n)}a=0;for(r=p.length;a<r;a++)l.push(p[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],t=g.vertexNormals,p=g.vertexColors,l=new Sa(g.a+e,g.b+e,g.c+e);l.normal.copy(g.normal);void 0!==d&&l.normal.applyMatrix3(d).normalize();b=0;for(f=t.length;b<f;b++)n=t[b].clone(),void 0!==d&&n.applyMatrix3(d).normalize(),l.vertexNormals.push(n);l.color.copy(g.color);b=0;for(f=p.length;b<f;b++)n=p[b],l.vertexColors.push(n.clone());l.materialIndex=g.materialIndex+
14265 c;h.push(l)}a=0;for(r=q.length;a<r;a++)if(c=q[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());m.push(d)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a)},mergeVertices:function(){var a={},b=[],c=[],d,e=Math.pow(10,4),f,g;f=0;for(g=this.vertices.length;f<
14266 g;f++)d=this.vertices[f],d=Math.round(d.x*e)+"_"+Math.round(d.y*e)+"_"+Math.round(d.z*e),void 0===a[d]?(a[d]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[d]];a=[];f=0;for(g=this.faces.length;f<g;f++)for(e=this.faces[f],e.a=c[e.a],e.b=c[e.b],e.c=c[e.c],e=[e.a,e.b,e.c],d=0;3>d;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,1),c=0,g=this.faceVertexUvs.length;c<g;c++)this.faceVertexUvs[c].splice(e,1);f=this.vertices.length-b.length;this.vertices=
14267 b;return f},sortFacesByMaterialIndex:function(){for(var a=this.faces,b=a.length,c=0;c<b;c++)a[c]._id=c;a.sort(function(a,b){return a.materialIndex-b.materialIndex});var d=this.faceVertexUvs[0],e=this.faceVertexUvs[1],f,g;d&&d.length===b&&(f=[]);e&&e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);g&&(this.faceVertexUvs[1]=g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+
14268 a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==l[b])return l[b];l[b]=q.length;q.push(a.getHex());return l[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=p.length/2;p.push(a.x,a.y);return r[b]}var e={metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==
14269 this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],m={},q=[],l={},p=[],r={};for(g=0;g<this.faces.length;g++){var n=this.faces[g],t=void 0!==this.faceVertexUvs[0][g],y=0<n.normal.length(),x=0<n.vertexNormals.length,u=1!==n.color.r||1!==n.color.g||1!==n.color.b,H=0<n.vertexColors.length,w=0,w=a(w,0,0),w=a(w,1,!0),w=a(w,2,!1),w=a(w,3,t),w=a(w,4,y),w=a(w,5,x),w=a(w,6,
14270 u),w=a(w,7,H);h.push(w);h.push(n.a,n.b,n.c);h.push(n.materialIndex);t&&(t=this.faceVertexUvs[0][g],h.push(d(t[0]),d(t[1]),d(t[2])));y&&h.push(b(n.normal));x&&(y=n.vertexNormals,h.push(b(y[0]),b(y[1]),b(y[2])));u&&h.push(c(n.color));H&&(n=n.vertexColors,h.push(c(n[0]),c(n[1]),c(n[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<q.length&&(e.data.colors=q);0<p.length&&(e.data.uvs=[p]);e.data.faces=h;return e},clone:function(){return(new J).copy(this)},copy:function(a){var b,c,d,e,f,g;this.vertices=
14271 [];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;d=a.vertices;b=0;for(c=d.length;b<c;b++)this.vertices.push(d[b].clone());d=a.colors;b=0;for(c=d.length;b<c;b++)this.colors.push(d[b].clone());d=a.faces;b=0;for(c=d.length;b<c;b++)this.faces.push(d[b].clone());b=0;for(c=a.faceVertexUvs.length;b<c;b++){var h=a.faceVertexUvs[b];void 0===
14272 this.faceVertexUvs[b]&&(this.faceVertexUvs[b]=[]);d=0;for(e=h.length;d<e;d++){var k=h[d],m=[];f=0;for(g=k.length;f<g;f++)m.push(k[f].clone());this.faceVertexUvs[b].push(m)}}f=a.morphTargets;b=0;for(c=f.length;b<c;b++){g={};g.name=f[b].name;if(void 0!==f[b].vertices)for(g.vertices=[],d=0,e=f[b].vertices.length;d<e;d++)g.vertices.push(f[b].vertices[d].clone());if(void 0!==f[b].normals)for(g.normals=[],d=0,e=f[b].normals.length;d<e;d++)g.normals.push(f[b].normals[d].clone());this.morphTargets.push(g)}f=
14273 a.morphNormals;b=0;for(c=f.length;b<c;b++){g={};if(void 0!==f[b].vertexNormals)for(g.vertexNormals=[],d=0,e=f[b].vertexNormals.length;d<e;d++)h=f[b].vertexNormals[d],k={},k.a=h.a.clone(),k.b=h.b.clone(),k.c=h.c.clone(),g.vertexNormals.push(k);if(void 0!==f[b].faceNormals)for(g.faceNormals=[],d=0,e=f[b].faceNormals.length;d<e;d++)g.faceNormals.push(f[b].faceNormals[d].clone());this.morphNormals.push(g)}d=a.skinWeights;b=0;for(c=d.length;b<c;b++)this.skinWeights.push(d[b].clone());d=a.skinIndices;b=
14274 0;for(c=d.length;b<c;b++)this.skinIndices.push(d[b].clone());d=a.lineDistances;b=0;for(c=d.length;b<c;b++)this.lineDistances.push(d[b]);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;
14275 this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(Z.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(Z.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=
14276 new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",
14277 d),f=new G);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=
14278 a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new n);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new fa);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*
14279 this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+
14280 1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,this.itemSize)).copy(this)}});pc.prototype=Object.create(Z.prototype);pc.prototype.constructor=pc;qc.prototype=Object.create(Z.prototype);
14281 qc.prototype.constructor=qc;rc.prototype=Object.create(Z.prototype);rc.prototype.constructor=rc;sc.prototype=Object.create(Z.prototype);sc.prototype.constructor=sc;gb.prototype=Object.create(Z.prototype);gb.prototype.constructor=gb;tc.prototype=Object.create(Z.prototype);tc.prototype.constructor=tc;hb.prototype=Object.create(Z.prototype);hb.prototype.constructor=hb;B.prototype=Object.create(Z.prototype);B.prototype.constructor=B;uc.prototype=Object.create(Z.prototype);uc.prototype.constructor=uc;
14282 Object.assign(Je.prototype,{computeGroups:function(a){var b,c=[],d=void 0;a=a.faces;for(var e=0;e<a.length;e++){var f=a[e];f.materialIndex!==d&&(d=f.materialIndex,void 0!==b&&(b.count=3*e-b.start,c.push(b)),b={start:3*e,materialIndex:d})}void 0!==b&&(b.count=3*e-b.start,c.push(b));this.groups=c},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=
14283 k}var q=a.morphNormals,l=q.length,p;if(0<l){p=[];for(m=0;m<l;m++)p[m]=[];this.morphTargets.normal=p}for(var r=a.skinIndices,n=a.skinWeights,t=r.length===c.length,y=n.length===c.length,m=0;m<b.length;m++){var x=b[m];this.vertices.push(c[x.a],c[x.b],c[x.c]);var u=x.vertexNormals;3===u.length?this.normals.push(u[0],u[1],u[2]):(u=x.normal,this.normals.push(u,u,u));u=x.vertexColors;3===u.length?this.colors.push(u[0],u[1],u[2]):(u=x.color,this.colors.push(u,u,u));!0===e&&(u=d[0][m],void 0!==u?this.uvs.push(u[0],
14284 u[1],u[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new C,new C,new C)));!0===f&&(u=d[1][m],void 0!==u?this.uvs2.push(u[0],u[1],u[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",m),this.uvs2.push(new C,new C,new C)));for(u=0;u<h;u++){var H=g[u].vertices;k[u].push(H[x.a],H[x.b],H[x.c])}for(u=0;u<l;u++)H=q[u].vertexNormals[m],p[u].push(H.a,H.b,H.c);t&&this.skinIndices.push(r[x.a],r[x.b],r[x.c]);y&&this.skinWeights.push(n[x.a],
14285 n[x.b],n[x.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});E.MaxIndex=65535;Object.assign(E.prototype,xa.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Sd(a)?hb:gb)(a,1):this.index=a},addAttribute:function(a,b,c){if(b&&b.isBufferAttribute||
14286 b&&b.isInterleavedBufferAttribute)if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this;else console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new Z(b,c))},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==
14287 c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new Ba).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);
14288 this.applyMatrix(a);return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new z;return function(b){a.lookAt(b);
14289 a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new B(3*b.vertices.length,3);var c=new B(3*b.colors.length,3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new B(b.lineDistances.length,
14290 1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=
14291 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=
14292 !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},
14293 fromGeometry:function(a){a.__directGeometry=(new Je).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new Z(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new Z(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new Z(b,3)).copyColorsArray(a.colors)));
14294 0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new Z(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new Z(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Sd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new Z(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],
14295 h=new B(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new B(4*a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new B(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===
14296 this.boundingBox&&(this.boundingBox=new Ra);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new Ra,b=new n;return function(){null===this.boundingSphere&&
14297 (this.boundingSphere=new Ea);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},
14298 computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;if(void 0===b.normal)this.addAttribute("normal",new Z(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h,k,m,q=new n,l=new n,p=new n,r=new n,ca=new n;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,y=c.length;t<y;++t)for(f=c[t],g=f.start,h=f.count,f=g,g+=h;f<g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],
14299 q.fromArray(d,h),l.fromArray(d,k),p.fromArray(d,m),r.subVectors(p,l),ca.subVectors(q,l),r.cross(ca),e[h]+=r.x,e[h+1]+=r.y,e[h+2]+=r.z,e[k]+=r.x,e[k+1]+=r.y,e[k+2]+=r.z,e[m]+=r.x,e[m+1]+=r.y,e[m+2]+=r.z}else for(f=0,g=d.length;f<g;f+=9)q.fromArray(d,f),l.fromArray(d,f+3),p.fromArray(d,f+6),r.subVectors(p,l),ca.subVectors(q,l),r.cross(ca),e[f]=r.x,e[f+1]=r.y,e[f+2]=r.z,e[f+3]=r.x,e[f+4]=r.y,e[f+5]=r.z,e[f+6]=r.x,e[f+7]=r.y,e[f+8]=r.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,
14300 b){if(a&&a.isBufferGeometry){void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a)},normalizeNormals:function(){for(var a=this.attributes.normal,b,c,d,e,f=0,g=a.count;f<g;f++)b=a.getX(f),c=a.getY(f),d=a.getZ(f),e=1/Math.sqrt(b*b+c*c+d*d),a.setXYZ(f,b*e,c*e,d*e)},toNonIndexed:function(){if(null===
14301 this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),this;var a=new E,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,m=0,q=b.length;m<q;m++){h=b[m]*e;for(var l=0;l<e;l++)g[k++]=f[h++]}a.addAttribute(d,new Z(g,e))}return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&
14302 (a.name=this.name);if(void 0!==this.parameters){var b=this.parameters,c;for(c in b)void 0!==b[c]&&(a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c],b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));
14303 c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),radius:c.radius});return a},clone:function(){return(new E).copy(this)},copy:function(a){var b,c,d;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(b in c)this.addAttribute(b,c[b].clone());var e=a.morphAttributes;for(b in e){var f=[],g=e[b];c=0;for(d=g.length;c<d;c++)f.push(g[c].clone());
14304 this.morphAttributes[b]=f}b=a.groups;c=0;for(d=b.length;c<d;c++)e=b[c],this.addGroup(e.start,e.count,e.materialIndex);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Gb.prototype=Object.create(J.prototype);Gb.prototype.constructor=Gb;ib.prototype=Object.create(E.prototype);ib.prototype.constructor=
14305 ib;vc.prototype=Object.create(J.prototype);vc.prototype.constructor=vc;jb.prototype=Object.create(E.prototype);jb.prototype.constructor=jb;ya.prototype=Object.create(U.prototype);ya.prototype.constructor=ya;ya.prototype.isMeshBasicMaterial=!0;ya.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.specularMap=a.specularMap;this.alphaMap=
14306 a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;return this};Object.assign(kb.prototype,{set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},
14307 copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new n).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new n;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){var c=b||new n;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},
14308 distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new n;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new n,b=new n,c=new n;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);
14309 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),q=-c.dot(b),l=c.lengthSq(),p=Math.abs(1-k*k),r;0<p?(d=k*q-m,e=k*m-q,r=h*p,0<=d?e>=-r?e<=r?(h=1/p,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*q)+l):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-q),h),k=-d*d+e*(e+2*q)+l):e<=r?(d=0,e=Math.min(Math.max(-h,-q),h),k=e*(e+2*q)+l):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
14310 -q),h),k=-d*d+e*(e+2*q)+l)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l);f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new n;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d,f=b.radius*b.radius;if(e>f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=
14311 a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;
14312 var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(f<d||d!==d)d=f;0<=g?(e=(a.min.z-h.z)*g,g*=a.max.z-h.z):(e=(a.max.z-h.z)*g,g*=a.min.z-h.z);if(c>g||e>d)return null;if(e>c||c!==c)c=e;if(g<d||d!==d)d=g;return 0>d?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new n;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=
14313 new n,b=new n,c=new n,d=new n;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0<f){if(h)return null;h=1}else if(0>f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},
14314 equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Hb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){return(a||new n).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new n).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},
14315 distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new n;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new n,b=new n;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=Y.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new n;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);
14316 this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Ta,{normal:function(){var a=new n;return function(b,c,d,e){e=e||new n;e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new n,b=new n,c=new n;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=
14317 b.dot(b);g=b.dot(c);var m=d*k-e*e;h=h||new n;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new n;return function(b,c,d,e){b=Ta.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Ta.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},
14318 copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new n,b=new n;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new n).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Ta.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new Aa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Ta.barycoordFromPoint(a,
14319 this.a,this.b,this.c,b)},containsPoint:function(a){return Ta.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new Aa,b=[new Hb,new Hb,new Hb],c=new n,d=new n;return function(e,f){var g=f||new n,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k<b.length;k++){b[k].closestPointToPoint(c,!0,d);var m=c.distanceToSquared(d);
14320 m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});la.prototype=Object.assign(Object.create(z.prototype),{constructor:la,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){z.prototype.copy.call(this,a);this.drawMode=a.drawMode;return this},updateMorphTargets:function(){var a=this.geometry,b,c;if(a.isBufferGeometry){if(a=a.morphAttributes,b=Object.keys(a),0<b.length){var d=a[b[0]];if(void 0!==d)for(this.morphTargetInfluences=
14321 [],this.morphTargetDictionary={},a=0,b=d.length;a<b;a++)c=d[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a}}else if(d=a.morphTargets,void 0!==d&&0<d.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=d.length;a<b;a++)c=d[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a},raycast:function(){function a(a,b,c,d,e,f,g){Ta.barycoordFromPoint(a,b,c,d,t);e.multiplyScalar(t.x);f.multiplyScalar(t.y);g.multiplyScalar(t.z);
14322 e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;x.copy(g);x.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(x);return c<b.near||c>b.far?null:{distance:c,point:x.clone(),object:a}}function c(c,d,e,f,m,q,l,n){g.fromBufferAttribute(f,q);h.fromBufferAttribute(f,l);k.fromBufferAttribute(f,n);if(c=b(c,d,e,g,h,k,y))m&&(p.fromBufferAttribute(m,q),r.fromBufferAttribute(m,
14323 l),ca.fromBufferAttribute(m,n),c.uv=a(y,g,h,k,p,r,ca)),c.face=new Sa(q,l,n,Ta.normal(g,h,k)),c.faceIndex=q;return c}var d=new K,e=new kb,f=new Ea,g=new n,h=new n,k=new n,m=new n,q=new n,l=new n,p=new C,r=new C,ca=new C,t=new n,y=new n,x=new n;return function(n,t){var w=this.geometry,x=this.material,B=this.matrixWorld;if(void 0!==x&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere),f.applyMatrix4(B),!1!==n.ray.intersectsSphere(f)&&(d.getInverse(B),e.copy(n.ray).applyMatrix4(d),
14324 null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var D;if(w.isBufferGeometry){var O,C,x=w.index,F=w.attributes.position,B=w.attributes.uv,z,T;if(null!==x)for(z=0,T=x.count;z<T;z+=3){if(w=x.getX(z),O=x.getX(z+1),C=x.getX(z+2),D=c(this,n,e,F,B,w,O,C))D.faceIndex=Math.floor(z/3),t.push(D)}else for(z=0,T=F.count;z<T;z+=3)if(w=z,O=z+1,C=z+2,D=c(this,n,e,F,B,w,O,C))D.index=w,t.push(D)}else if(w.isGeometry){var E,B=Array.isArray(x);z=w.vertices;T=w.faces;O=w.faceVertexUvs[0];0<O.length&&(F=O);
14325 for(var G=0,K=T.length;G<K;G++){var P=T[G];D=B?x[P.materialIndex]:x;if(void 0!==D){O=z[P.a];C=z[P.b];E=z[P.c];if(!0===D.morphTargets){D=w.morphTargets;var M=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var V=0,pa=D.length;V<pa;V++){var S=M[V];if(0!==S){var N=D[V].vertices;g.addScaledVector(m.subVectors(N[P.a],O),S);h.addScaledVector(q.subVectors(N[P.b],C),S);k.addScaledVector(l.subVectors(N[P.c],E),S)}}g.add(O);h.add(C);k.add(E);O=g;C=h;E=k}if(D=b(this,n,e,O,C,E,y))F&&F[G]&&
14326 (M=F[G],p.copy(M[0]),r.copy(M[1]),ca.copy(M[2]),D.uv=a(y,O,C,E,p,r,ca)),D.face=P,D.faceIndex=G,t.push(D)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});var bg=0;kd.prototype=Object.assign(Object.create(qa.prototype),{constructor:kd,isArrayCamera:!0});Ib.prototype.isFogExp2=!0;Ib.prototype.clone=function(){return new Ib(this.color.getHex(),this.density)};Ib.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};
14327 Jb.prototype.isFog=!0;Jb.prototype.clone=function(){return new Jb(this.color.getHex(),this.near,this.far)};Jb.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};ld.prototype=Object.assign(Object.create(z.prototype),{constructor:ld,copy:function(a,b){z.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());
14328 this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=z.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Yd.prototype=Object.assign(Object.create(z.prototype),{constructor:Yd,isLensFlare:!0,copy:function(a){z.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=
14329 0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new G(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;a<b;a++)c=this.lensFlares[a],
14330 c.x=this.positionScreen.x+d*c.distance,c.y=this.positionScreen.y+e*c.distance,c.wantedRotation=c.x*Math.PI*.25,c.rotation+=.25*(c.wantedRotation-c.rotation)}});bb.prototype=Object.create(U.prototype);bb.prototype.constructor=bb;bb.prototype.isSpriteMaterial=!0;bb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};xc.prototype=Object.assign(Object.create(z.prototype),{constructor:xc,isSprite:!0,raycast:function(){var a=
14331 new n,b=new n,c=new n;return function(d,e){b.setFromMatrixPosition(this.matrixWorld);d.ray.closestPointToPoint(b,a);c.setFromMatrixScale(this.matrixWorld);var f=c.x*c.y/4;b.distanceToSquared(a)>f||(f=d.ray.origin.distanceTo(a),f<d.near||f>d.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});yc.prototype=Object.assign(Object.create(z.prototype),{constructor:yc,copy:function(a){z.prototype.copy.call(this,a,
14332 !1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-1].object},raycast:function(){var a=new n;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=
14333 b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new n,b=new n;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=z.prototype.toJSON.call(this,a);a.object.levels=
14334 [];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(zc.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new K;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b,c;b=0;for(c=this.bones.length;b<c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<
14335 c;b++)if(a=this.bones[b])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new K,b=new K;return function(){for(var c=this.bones,d=this.boneInverses,e=this.boneMatrices,f=this.boneTexture,g=0,h=c.length;g<h;g++)a.multiplyMatrices(c[g]?c[g].matrixWorld:b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new zc(this.bones,
14336 this.boneInverses)}});md.prototype=Object.assign(Object.create(z.prototype),{constructor:md,isBone:!0});nd.prototype=Object.assign(Object.create(la.prototype),{constructor:nd,isSkinnedMesh:!0,initBones:function(){var a=[],b,c,d,e;if(this.geometry&&void 0!==this.geometry.bones){d=0;for(e=this.geometry.bones.length;d<e;d++)c=this.geometry.bones[d],b=new md,a.push(b),b.name=c.name,b.position.fromArray(c.pos),b.quaternion.fromArray(c.rotq),void 0!==c.scl&&b.scale.fromArray(c.scl);d=0;for(e=this.geometry.bones.length;d<
14337 e;d++)c=this.geometry.bones[d],-1!==c.parent&&null!==c.parent&&void 0!==a[c.parent]?a[c.parent].add(a[d]):this.add(a[d])}this.updateMatrixWorld(!0);return a},bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var a,b;if(this.geometry&&this.geometry.isGeometry)for(b=0;b<this.geometry.skinWeights.length;b++){var c=
14338 this.geometry.skinWeights[b];a=1/c.lengthManhattan();Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var c=new fa,d=this.geometry.attributes.skinWeight;for(b=0;b<d.count;b++)c.x=d.getX(b),c.y=d.getY(b),c.z=d.getZ(b),c.w=d.getW(b),a=1/c.lengthManhattan(),Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0),d.setXYZW(b,c.x,c.y,c.z,c.w)}},updateMatrixWorld:function(a){la.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):
14339 "detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});ea.prototype=Object.create(U.prototype);ea.prototype.constructor=ea;ea.prototype.isLineBasicMaterial=!0;ea.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;
14340 return this};sa.prototype=Object.assign(Object.create(z.prototype),{constructor:sa,isLine:!0,raycast:function(){var a=new K,b=new kb,c=new Ea;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new n,m=new n,h=new n,q=new n,l=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var p=g.index,
14341 r=g.attributes.position.array;if(null!==p)for(var p=p.array,g=0,ca=p.length-1;g<ca;g+=l){var t=p[g+1];k.fromArray(r,3*p[g]);m.fromArray(r,3*t);t=b.distanceSqToSegment(k,m,q,h);t>f||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,ca=r.length/3-1;g<ca;g+=l)k.fromArray(r,3*g),m.fromArray(r,3*g+3),t=b.distanceSqToSegment(k,m,q,h),t>f||(q.applyMatrix4(this.matrixWorld),
14342 t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=l)t=b.distanceSqToSegment(k[g],k[g+1],q,h),t>f||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,
14343 this.material)).copy(this)}});Q.prototype=Object.assign(Object.create(sa.prototype),{constructor:Q,isLineSegments:!0});od.prototype=Object.assign(Object.create(sa.prototype),{constructor:od,isLineLoop:!0});Fa.prototype=Object.create(U.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isPointsMaterial=!0;Fa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(z.prototype),
14344 {constructor:Kb,isPoints:!0,raycast:function(){var a=new K,b=new kb,c=new Ea;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<q){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);
14345 c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),q=m*m,m=new n;if(h.isBufferGeometry){var l=h.index,h=h.attributes.position.array;if(null!==l)for(var p=l.array,l=0,r=p.length;l<r;l++){var ca=p[l];m.fromArray(h,3*ca);f(m,ca)}else for(l=0,p=h.length/3;l<p;l++)m.fromArray(h,3*l),f(m,l)}else for(m=h.vertices,l=0,p=m.length;l<p;l++)f(m[l],l)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});
14346 Ac.prototype=Object.assign(Object.create(z.prototype),{constructor:Ac});pd.prototype=Object.create(ba.prototype);pd.prototype.constructor=pd;Lb.prototype=Object.create(ba.prototype);Lb.prototype.constructor=Lb;Lb.prototype.isCompressedTexture=!0;qd.prototype=Object.create(ba.prototype);qd.prototype.constructor=qd;Bc.prototype=Object.create(ba.prototype);Bc.prototype.constructor=Bc;Bc.prototype.isDepthTexture=!0;Mb.prototype=Object.create(E.prototype);Mb.prototype.constructor=Mb;Cc.prototype=Object.create(J.prototype);
14347 Cc.prototype.constructor=Cc;Nb.prototype=Object.create(E.prototype);Nb.prototype.constructor=Nb;Dc.prototype=Object.create(J.prototype);Dc.prototype.constructor=Dc;za.prototype=Object.create(E.prototype);za.prototype.constructor=za;Ec.prototype=Object.create(J.prototype);Ec.prototype.constructor=Ec;Ob.prototype=Object.create(za.prototype);Ob.prototype.constructor=Ob;Fc.prototype=Object.create(J.prototype);Fc.prototype.constructor=Fc;lb.prototype=Object.create(za.prototype);lb.prototype.constructor=
14348 lb;Gc.prototype=Object.create(J.prototype);Gc.prototype.constructor=Gc;Pb.prototype=Object.create(za.prototype);Pb.prototype.constructor=Pb;Hc.prototype=Object.create(J.prototype);Hc.prototype.constructor=Hc;Qb.prototype=Object.create(za.prototype);Qb.prototype.constructor=Qb;Ic.prototype=Object.create(J.prototype);Ic.prototype.constructor=Ic;Rb.prototype=Object.create(E.prototype);Rb.prototype.constructor=Rb;Jc.prototype=Object.create(J.prototype);Jc.prototype.constructor=Jc;Sb.prototype=Object.create(E.prototype);
14349 Sb.prototype.constructor=Sb;Kc.prototype=Object.create(J.prototype);Kc.prototype.constructor=Kc;Tb.prototype=Object.create(E.prototype);Tb.prototype.constructor=Tb;var Ia={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<Ia.area(a))for(h=0;h<c;h++)e[h]=h;else for(h=0;h<c;h++)e[h]=c-1-h;var m=2*c;for(h=c-1;2<c;){if(0>=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");
14350 break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var q;a:{var l,p,r,n,t,y,x,u;l=a[e[g]].x;p=a[e[g]].y;r=a[e[h]].x;n=a[e[h]].y;t=a[e[k]].x;y=a[e[k]].y;if(0>=(r-l)*(y-p)-(n-p)*(t-l))q=!1;else{var H,w,I,z,D,O,B,C,E,G;H=t-r;w=y-n;I=l-t;z=p-y;D=r-l;O=n-p;for(q=0;q<c;q++)if(x=a[e[q]].x,u=a[e[q]].y,!(x===l&&u===p||x===r&&u===n||x===t&&u===y)&&(B=x-l,C=u-p,E=x-r,G=u-n,x-=t,u-=y,E=H*G-w*E,B=D*C-O*B,C=I*u-z*x,E>=-Number.EPSILON&&C>=-Number.EPSILON&&B>=-Number.EPSILON)){q=!1;break a}q=!0}}if(q){d.push([a[e[g]],
14351 a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;k<c;g++,k++)e[g]=e[k];c--;m=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,m=e.y-c.y,q=a.x-c.x,l=a.y-c.y,p=h*k-g*m,n=h*q-g*l;if(Math.abs(p)>Number.EPSILON){if(0<p){if(0>n||n>p)return[];k=m*q-k*
14352 l;if(0>k||k>p)return[]}else{if(0<n||n<p)return[];k=m*q-k*l;if(0<k||k<p)return[]}if(0===k)return!f||0!==n&&n!==p?[a]:[];if(k===p)return!f||0!==n&&n!==p?[b]:[];if(0===n)return[c];if(n===p)return[e];f=k/p;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==n||m*q!==k*l)return[];h=0===g&&0===h;k=0===k&&0===m;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,p=c.x,m=e,c=e.x):(b=e,p=e.x,m=c,c=c.x)):
14353 (a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,p=c.y,m=e,c=e.y):(b=e,p=e.y,m=c,c=c.y));return k<=p?a<p?[]:a===p?f?[]:[b]:a<=c?[b,h]:[b,m]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h,k,m,q,l={};k=a.concat();g=0;for(h=b.length;g<h;g++)Array.prototype.push.apply(k,b[g]);g=0;for(h=
14354 k.length;g<h;g++)q=k[g].x+":"+k[g].y,void 0!==l[q]&&console.warn("THREE.ShapeUtils: Duplicate point",q,g),l[q]=g;g=function(a,b){function c(a,b){var d=h.length-1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;c<h.length;c++)if(f=c+1,f%=h.length,f=e(a,b,h[c],h[f],!0),0<f.length)return!0;return!1}function g(a,c){var d,f,h,k;for(d=0;d<m.length;d++)for(f=
14355 b[m[d]],h=0;h<f.length;h++)if(k=h+1,k%=f.length,k=e(a,c,f[h],f[k],!0),0<k.length)return!0;return!1}var h=a.concat(),k,m=[],q,l,p,n,v,B=[],C,z,E,G=0;for(q=b.length;G<q;G++)m.push(G);C=0;for(var K=2*m.length;0<m.length;){K--;if(0>K){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(l=C;l<h.length;l++){p=h[l];q=-1;for(G=0;G<m.length;G++)if(n=m[G],v=p.x+":"+p.y+":"+n,void 0===B[v]){k=b[n];for(z=0;z<k.length;z++)if(n=k[z],c(l,z)&&!d(p,n)&&!g(p,n)){q=z;m.splice(G,
14356 1);C=h.slice(0,l+1);n=h.slice(l);z=k.slice(q);E=k.slice(0,q+1);h=C.concat(z).concat(E).concat(n);C=l;break}if(0<=q)break;B[v]=!0}if(0<=q)break}}return h}(a,b);var p=Ia.triangulate(g,!1);g=0;for(h=p.length;g<h;g++)for(m=p[g],k=0;3>k;k++)q=m[k].x+":"+m[k].y,q=l[q],void 0!==q&&(m[k]=q);return p.concat()},isClockWise:function(a){return 0>Ia.area(a)}};cb.prototype=Object.create(J.prototype);cb.prototype.constructor=cb;Ga.prototype=Object.create(E.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays=
14357 function(){var a=this.getAttribute("position"),a=a?Array.prototype.slice.call(a.array):[],b=this.getAttribute("uv"),b=b?Array.prototype.slice.call(b.array):[],c=this.index,c=c?Array.prototype.slice.call(c.array):[];return{position:a,uv:b,index:c}};Ga.prototype.addShapeList=function(a,b){var c=a.length;b.arrays=this.getArrays();for(var d=0;d<c;d++)this.addShape(a[d],b);this.setIndex(b.arrays.index);this.addAttribute("position",new B(b.arrays.position,3));this.addAttribute("uv",new B(b.arrays.uv,2))};
14358 Ga.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d,e,f;e=a.x-b.x;f=a.y-b.y;d=c.x-a.x;var g=c.y-a.y,h=e*e+f*f;if(Math.abs(e*g-f*d)>Number.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&
14359 (a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new C(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=H+2*y;for(e=0;e<f;e++){var g=ba*e,m=ba*(e+1),l=b+d+g,p=b+d+m,m=b+c+m;h(b+c+g);h(l);h(m);h(l);h(p);h(m);g=q.length/3;g=D.generateSideWallUV(Z,q,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);k(g[2]);k(g[3])}}}function f(a,b,c){r.push(a);r.push(b);r.push(c)}
14360 function g(a,b,c){h(a);h(b);h(c);a=q.length/3;a=D.generateTopUV(Z,q,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){l.push(q.length/3);q.push(r[3*a+0]);q.push(r[3*a+1]);q.push(r[3*a+2])}function k(a){p.push(a.x);p.push(a.y)}var m=b.arrays?b.arrays:this.getArrays(),q=m.position,l=m.index,p=m.uv,r=[],m=void 0!==b.amount?b.amount:100,z=void 0!==b.bevelThickness?b.bevelThickness:6,t=void 0!==b.bevelSize?b.bevelSize:z-2,y=void 0!==b.bevelSegments?b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:
14361 !0,u=void 0!==b.curveSegments?b.curveSegments:12,H=void 0!==b.steps?b.steps:1,w=b.extrudePath,I,G=!1,D=void 0!==b.UVGenerator?b.UVGenerator:cb.WorldUVGenerator,O,E,F,K;w&&(I=w.getSpacedPoints(H),G=!0,x=!1,O=void 0!==b.frames?b.frames:w.computeFrenetFrames(H,!1),E=new n,F=new n,K=new n);x||(t=z=y=0);var T,J,U,Z=this,w=a.extractPoints(u),u=w.shape,P=w.holes;if(!Ia.isClockWise(u))for(u=u.reverse(),J=0,U=P.length;J<U;J++)T=P[J],Ia.isClockWise(T)&&(P[J]=T.reverse());var M=Ia.triangulateShape(u,P),V=u;
14362 J=0;for(U=P.length;J<U;J++)T=P[J],u=u.concat(T);var R,S,N,Y,Q,ba=u.length,X,fa=M.length,w=[],L=0;N=V.length;R=N-1;for(S=L+1;L<N;L++,R++,S++)R===N&&(R=0),S===N&&(S=0),w[L]=d(V[L],V[R],V[S]);var ha=[],ea,ia=w.concat();J=0;for(U=P.length;J<U;J++){T=P[J];ea=[];L=0;N=T.length;R=N-1;for(S=L+1;L<N;L++,R++,S++)R===N&&(R=0),S===N&&(S=0),ea[L]=d(T[L],T[R],T[S]);ha.push(ea);ia=ia.concat(ea)}for(R=0;R<y;R++){N=R/y;Y=z*Math.cos(N*Math.PI/2);S=t*Math.sin(N*Math.PI/2);L=0;for(N=V.length;L<N;L++)Q=c(V[L],w[L],S),
14363 f(Q.x,Q.y,-Y);J=0;for(U=P.length;J<U;J++)for(T=P[J],ea=ha[J],L=0,N=T.length;L<N;L++)Q=c(T[L],ea[L],S),f(Q.x,Q.y,-Y)}S=t;for(L=0;L<ba;L++)Q=x?c(u[L],ia[L],S):u[L],G?(F.copy(O.normals[0]).multiplyScalar(Q.x),E.copy(O.binormals[0]).multiplyScalar(Q.y),K.copy(I[0]).add(F).add(E),f(K.x,K.y,K.z)):f(Q.x,Q.y,0);for(N=1;N<=H;N++)for(L=0;L<ba;L++)Q=x?c(u[L],ia[L],S):u[L],G?(F.copy(O.normals[N]).multiplyScalar(Q.x),E.copy(O.binormals[N]).multiplyScalar(Q.y),K.copy(I[N]).add(F).add(E),f(K.x,K.y,K.z)):f(Q.x,Q.y,
14364 m/H*N);for(R=y-1;0<=R;R--){N=R/y;Y=z*Math.cos(N*Math.PI/2);S=t*Math.sin(N*Math.PI/2);L=0;for(N=V.length;L<N;L++)Q=c(V[L],w[L],S),f(Q.x,Q.y,m+Y);J=0;for(U=P.length;J<U;J++)for(T=P[J],ea=ha[J],L=0,N=T.length;L<N;L++)Q=c(T[L],ea[L],S),G?f(Q.x,Q.y+I[H-1].y,I[H-1].x+Y):f(Q.x,Q.y,m+Y)}(function(){var a=q.length/3;if(x){var c=0*ba;for(L=0;L<fa;L++)X=M[L],g(X[2]+c,X[1]+c,X[0]+c);c=ba*(H+2*y);for(L=0;L<fa;L++)X=M[L],g(X[0]+c,X[1]+c,X[2]+c)}else{for(L=0;L<fa;L++)X=M[L],g(X[2],X[1],X[0]);for(L=0;L<fa;L++)X=
14365 M[L],g(X[0]+ba*H,X[1]+ba*H,X[2]+ba*H)}Z.addGroup(a,q.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=q.length/3,c=0;e(V,c);c+=V.length;J=0;for(U=P.length;J<U;J++)T=P[J],e(T,c),c+=T.length;Z.addGroup(a,q.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:1)})();b.arrays||(this.setIndex(l),this.addAttribute("position",new B(q,3)),this.addAttribute("uv",new B(b.arrays.uv,2)))};cb.WorldUVGenerator={generateTopUV:function(a,b,c,d,e){a=b[3*d];d=b[3*d+1];var f=b[3*e];e=b[3*e+1];return[new C(b[3*
14366 c],b[3*c+1]),new C(a,d),new C(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var m=b[3*e],l=b[3*e+1];e=b[3*e+2];var n=b[3*f],p=b[3*f+1];b=b[3*f+2];return.01>Math.abs(g-k)?[new C(a,1-c),new C(h,1-d),new C(m,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(l,1-e),new C(p,1-b)]}};Lc.prototype=Object.create(J.prototype);Lc.prototype.constructor=Lc;Ub.prototype=Object.create(Ga.prototype);Ub.prototype.constructor=Ub;Mc.prototype=
14367 Object.create(J.prototype);Mc.prototype.constructor=Mc;mb.prototype=Object.create(E.prototype);mb.prototype.constructor=mb;Nc.prototype=Object.create(J.prototype);Nc.prototype.constructor=Nc;Vb.prototype=Object.create(E.prototype);Vb.prototype.constructor=Vb;Oc.prototype=Object.create(J.prototype);Oc.prototype.constructor=Oc;Wb.prototype=Object.create(E.prototype);Wb.prototype.constructor=Wb;Xb.prototype=Object.create(J.prototype);Xb.prototype.constructor=Xb;Yb.prototype=Object.create(E.prototype);
14368 Yb.prototype.constructor=Yb;Zb.prototype=Object.create(E.prototype);Zb.prototype.constructor=Zb;nb.prototype=Object.create(J.prototype);nb.prototype.constructor=nb;Ua.prototype=Object.create(E.prototype);Ua.prototype.constructor=Ua;Pc.prototype=Object.create(nb.prototype);Pc.prototype.constructor=Pc;Qc.prototype=Object.create(Ua.prototype);Qc.prototype.constructor=Qc;Rc.prototype=Object.create(J.prototype);Rc.prototype.constructor=Rc;$b.prototype=Object.create(E.prototype);$b.prototype.constructor=
14369 $b;var Ma=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:Cc,ParametricBufferGeometry:Nb,TetrahedronGeometry:Ec,TetrahedronBufferGeometry:Ob,OctahedronGeometry:Fc,OctahedronBufferGeometry:lb,IcosahedronGeometry:Gc,IcosahedronBufferGeometry:Pb,DodecahedronGeometry:Hc,DodecahedronBufferGeometry:Qb,PolyhedronGeometry:Dc,PolyhedronBufferGeometry:za,TubeGeometry:Ic,TubeBufferGeometry:Rb,TorusKnotGeometry:Jc,TorusKnotBufferGeometry:Sb,TorusGeometry:Kc,TorusBufferGeometry:Tb,TextGeometry:Lc,TextBufferGeometry:Ub,
14370 SphereGeometry:Mc,SphereBufferGeometry:mb,RingGeometry:Nc,RingBufferGeometry:Vb,PlaneGeometry:vc,PlaneBufferGeometry:jb,LatheGeometry:Oc,LatheBufferGeometry:Wb,ShapeGeometry:Xb,ShapeBufferGeometry:Yb,ExtrudeGeometry:cb,ExtrudeBufferGeometry:Ga,EdgesGeometry:Zb,ConeGeometry:Pc,ConeBufferGeometry:Qc,CylinderGeometry:nb,CylinderBufferGeometry:Ua,CircleGeometry:Rc,CircleBufferGeometry:$b,BoxGeometry:Gb,BoxBufferGeometry:ib});ac.prototype=Object.create(ra.prototype);ac.prototype.constructor=ac;ac.prototype.isShadowMaterial=
14371 !0;bc.prototype=Object.create(ra.prototype);bc.prototype.constructor=bc;bc.prototype.isRawShaderMaterial=!0;Pa.prototype=Object.create(U.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=
14372 a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;
14373 this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ob.prototype=Object.create(Pa.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshPhysicalMaterial=!0;ob.prototype.copy=function(a){Pa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=
14374 a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ja.prototype=Object.create(U.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isMeshPhongMaterial=!0;Ja.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);
14375 this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;
14376 this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};pb.prototype=Object.create(Ja.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshToonMaterial=!0;pb.prototype.copy=function(a){Ja.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};qb.prototype=Object.create(U.prototype);qb.prototype.constructor=
14377 qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};
14378 rb.prototype=Object.create(U.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=
14379 a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};sb.prototype=Object.create(U.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=function(a){U.prototype.copy.call(this,
14380 a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var mg=Object.freeze({ShadowMaterial:ac,SpriteMaterial:bb,RawShaderMaterial:bc,ShaderMaterial:ra,PointsMaterial:Fa,MeshPhysicalMaterial:ob,MeshStandardMaterial:Pa,MeshPhongMaterial:Ja,MeshToonMaterial:pb,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:Za,MeshBasicMaterial:ya,LineDashedMaterial:sb,LineBasicMaterial:ea,Material:U}),ed={enabled:!1,files:{},
14381 add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},va=new Zd;Object.assign(Ka.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ed.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g=
14382 g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var n=new Uint8Array(m),k=0;k<g.length;k++)n[k]=g.charCodeAt(k);"blob"===l&&(m=new Blob([m],{type:h}));break;case "document":m=(new DOMParser).parseFromString(g,h);break;case "json":m=JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(r){window.setTimeout(function(){d&&d(r);
14383 e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{var p=new XMLHttpRequest;p.open("GET",a,!0);p.addEventListener("load",function(c){var f=c.target.response;ed.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemEnd(a),e.manager.itemError(a))},!1);void 0!==c&&p.addEventListener("progress",function(a){c(a)},!1);p.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);
14384 e.manager.itemError(a)},!1);void 0!==this.responseType&&(p.responseType=this.responseType);void 0!==this.withCredentials&&(p.withCredentials=this.withCredentials);p.overrideMimeType&&p.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)p.setRequestHeader(h,this.requestHeader[h]);p.send(null)}e.manager.itemStart(a);return p},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=a;return this},setWithCredentials:function(a){this.withCredentials=
14385 a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Oe.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Lb;h.image=g;var k=new Ka(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");
14386 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=
14387 a;return this}});Object.assign($d.prototype,{load:function(a,b,c,d){var e=this,f=new db,g=new Ka(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
14388 a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Sc.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ed.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;c=document.createElementNS("http://www.w3.org/1999/xhtml","img");
14389 c.addEventListener("load",function(){ed.add(a,this);b&&b(this);e.manager.itemEnd(a)},!1);c.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)},!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(ae.prototype,{load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=
14390 a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Xa,g=new Sc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(rd.prototype,{load:function(a,b,c,d){var e=new Sc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ba;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||
14391 0===a.search(/^data\:image\/jpeg/);f.format=c?1022:1023;f.needsUpdate=!0;void 0!==b&&b(f)},c,d);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});na.prototype=Object.assign(Object.create(z.prototype),{constructor:na,isLight:!0,copy:function(a){z.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=z.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=
14392 this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});sd.prototype=Object.assign(Object.create(na.prototype),{constructor:sd,isHemisphereLight:!0,copy:function(a){na.prototype.copy.call(this,
14393 a);this.groundColor.copy(a.groundColor);return this}});Object.assign(tb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;
14394 return a}});td.prototype=Object.assign(Object.create(tb.prototype),{constructor:td,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*Y.RAD2DEG*a.angle,d=this.mapSize.width/this.mapSize.height;a=a.distance||b.far;if(c!==b.fov||d!==b.aspect||a!==b.far)b.fov=c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});ud.prototype=Object.assign(Object.create(na.prototype),{constructor:ud,isSpotLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
14395 a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});vd.prototype=Object.assign(Object.create(na.prototype),{constructor:vd,isPointLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});wd.prototype=Object.assign(Object.create(tb.prototype),{constructor:wd});xd.prototype=Object.assign(Object.create(na.prototype),{constructor:xd,isDirectionalLight:!0,copy:function(a){na.prototype.copy.call(this,
14396 a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});yd.prototype=Object.assign(Object.create(na.prototype),{constructor:yd,isAmbientLight:!0});zd.prototype=Object.assign(Object.create(na.prototype),{constructor:zd,isRectAreaLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=na.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var ia={arraySlice:function(a,
14397 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=
14398 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++];
14399 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=
14400 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]=
14401 c[a+e];return b},interpolate_:function(a,b,c,d){throw Error("call to abstract method");},intervalChanged_:function(a,b,c){}});Object.assign(wa.prototype,{beforeStart_:wa.prototype.copySampleValue_,afterEnd_:wa.prototype.copySampleValue_});Ad.prototype=Object.assign(Object.create(wa.prototype),{constructor:Ad,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=
14402 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,
14403 p=(c-b)/(d-b);c=p*p;d=c*p;b=-l*d+2*l*c-l*p;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+p*f[a+c]+n*f[m+c];return e}});Tc.prototype=Object.assign(Object.create(wa.prototype),{constructor:Tc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Bd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Bd,
14404 interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Wa;Wa={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Bd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Tc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Ad(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){var b;
14405 switch(a){case 2300:b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn("THREE.KeyframeTrackPrototype:",b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;
14406 case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302}},getValueSize:function(){return this.values.length/this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,
14407 1),e=f-1),d=this.getValueSize(),this.times=ia.arraySlice(c,e,f),this.values=ia.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",
14408 this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&ia.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==
14409 k[0]))if(d)h=!0;else for(var m=g*c,l=m-c,n=m+c,k=0;k!==c;++k){var p=b[m+k];if(p!==b[l+k]||p!==b[n+k]){h=!0;break}}if(h){if(g!==e)for(a[e]=a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=ia.arraySlice(a,0,e),this.values=ia.arraySlice(b,0,e*c));return this}};cc.prototype=Object.assign(Object.create(Wa),{constructor:cc,ValueTypeName:"vector"});Cd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Cd,
14410 interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)oa.slerpFlat(e,0,f,a-g,f,a,b);return e}});Uc.prototype=Object.assign(Object.create(Wa),{constructor:Uc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Cd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});dc.prototype=Object.assign(Object.create(Wa),{constructor:dc,ValueTypeName:"number"});
14411 Dd.prototype=Object.assign(Object.create(Wa),{constructor:Dd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Ed.prototype=Object.assign(Object.create(Wa),{constructor:Ed,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Fd.prototype=Object.assign(Object.create(Wa),{constructor:Fd,ValueTypeName:"color"});
14412 vb.prototype=Wa;Wa.constructor=vb;Object.assign(vb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=vb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];ia.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:ia.convertArray(a.times,Array),values:ia.convertArray(a.values,
14413 Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return dc;case "vector":case "vector2":case "vector3":case "vector4":return cc;case "color":return Fd;case "quaternion":return Uc;case "bool":case "boolean":return Ed;case "string":return Dd}throw Error("Unsupported typeName: "+a);}});Object.assign(Da,{parse:function(a){for(var b=
14414 [],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(vb.parse(c[e]).scale(d));return new Da(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==e;++d)b.push(vb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var m=ia.getKeyframeOrder(h),h=ia.sortedArray(h,1,m),k=ia.sortedArray(k,1,m);d||0!==h[0]||
14415 (h.push(e),k.push(k[0]));f.push((new dc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new Da(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(var d=0;d<c.length;d++)if(c[d].name===b)return c[d];return null},CreateClipsFromMorphTargetSequences:function(a,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];
14416 for(m in d)a.push(Da.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;for(var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];ia.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30,h=a.hierarchy||[],k=0;k<h.length;k++){var m=h[k].keys;if(m&&0!==m.length)if(m[0].morphTargets){for(var f={},l=0;l<m.length;l++)if(m[l].morphTargets)for(var n=
14417 0;n<m[l].morphTargets.length;n++)f[m[l].morphTargets[n]]=-1;for(var p in f){for(var r=[],z=[],n=0;n!==m[l].morphTargets.length;++n){var t=m[l];r.push(t.time);z.push(t.morphTarget===p?1:0)}d.push(new dc(".morphTargetInfluence["+p+"]",r,z))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(cc,l+".position",m,"pos",d),c(Uc,l+".quaternion",m,"rot",d),c(cc,l+".scale",m,"scl",d)}return 0===d.length?null:new Da(e,f,d)}});Object.assign(Da.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==
14418 c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Gd.prototype,{load:function(a,b,c,d){var e=this;(new Ka(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===
14419 c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new mg[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=
14420 a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==a.fog&&(d.fog=a.fog);void 0!==a.shading&&(d.shading=a.shading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);
14421 void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=a.wireframe);void 0!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);
14422 void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=a.morphTargets);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&
14423 (e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);
14424 void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));return d}});Object.assign(be.prototype,{load:function(a,b,c,d){var e=
14425 this;(new Ka(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new E,c=a.data.index;void 0!==c&&(c=new ef[c.type](c.array),b.setIndex(new Z(c,1)));var d=a.data.attributes,e;for(e in d){var f=d[e],c=new ef[f.type](f.array);b.addAttribute(e,new Z(c,f.itemSize,f.normalized))}e=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==e)for(c=0,d=e.length;c!==d;++c)f=e[c],b.addGroup(f.start,f.count,f.materialIndex);a=a.data.boundingSphere;void 0!==a&&(e=new n,void 0!==
14426 a.center&&e.fromArray(a.center),b.boundingSphere=new Ea(e,a.radius));return b}});var ef={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};ec.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=
14427 b[c+1];if(b[c].test(a))return e}return null}};Object.assign(ec.prototype,{crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},b=new G,c=new rd,d=new Gd;return function(e,f,g){function h(a,
14428 b,d,e,h){a=f+a;var m=ec.Handlers.get(a);null!==m?a=m.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==h&&(a.anisotropy=h);b=Y.generateUUID();k[b]=a;return b}var k={},m={uuid:Y.generateUUID(),type:"MeshLambertMaterial"},l;for(l in e){var n=e[l];
14429 switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=n;break;case "blending":m.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");break;case "colorDiffuse":m.color=b.fromArray(n).getHex();break;case "colorSpecular":m.specular=b.fromArray(n).getHex();break;case "colorEmissive":m.emissive=b.fromArray(n).getHex();break;case "specularCoef":m.shininess=n;break;case "shading":"basic"===
14430 n.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":m.emissiveMap=h(n,e.mapEmissiveRepeat,e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);
14431 break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":m.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":m.bumpMap=
14432 h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":m.normalScale=[n,n];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=
14433 h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":m.roughnessMap=h(n,e.mapRoughnessRepeat,
14434 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":m.side=1;break;case "doubleSided":m.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
14435 m.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=n;break;case "vertexColors":!0===n&&(m.vertexColors=2);"face"===n&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,n)}}"MeshBasicMaterial"===m.type&&delete m.emissive;"MeshPhongMaterial"!==m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});Object.assign(ce.prototype,
14436 {load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:ec.prototype.extractUrlBase(a),g=new Ka(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");
14437 return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new J,d=a,e,f,g,h,k,m,l,v,p,r,z,t,y,x,u=d.faces;p=d.vertices;var B=d.normals,w=d.colors;m=d.scale;var I=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&I++;for(e=0;e<I;e++)c.faceVertexUvs[e]=[]}h=0;for(k=p.length;h<k;)e=new n,e.x=p[h++]*m,e.y=p[h++]*m,e.z=p[h++]*m,c.vertices.push(e);
14438 h=0;for(k=u.length;h<k;)if(p=u[h++],r=p&1,g=p&2,e=p&8,l=p&16,z=p&32,m=p&64,p&=128,r){r=new Sa;r.a=u[h];r.b=u[h+1];r.c=u[h+3];t=new Sa;t.a=u[h+1];t.b=u[h+2];t.c=u[h+3];h+=4;g&&(g=u[h++],r.materialIndex=g,t.materialIndex=g);g=c.faces.length;if(e)for(e=0;e<I;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=[],c.faceVertexUvs[e][g+1]=[],f=0;4>f;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),2!==f&&c.faceVertexUvs[e][g].push(x),0!==f&&c.faceVertexUvs[e][g+1].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]),
14439 t.normal.copy(r.normal));if(z)for(e=0;4>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),2!==e&&r.vertexNormals.push(z),0!==e&&t.vertexNormals.push(z);m&&(m=u[h++],m=w[m],r.color.setHex(m),t.color.setHex(m));if(p)for(e=0;4>e;e++)m=u[h++],m=w[m],2!==e&&r.vertexColors.push(new G(m)),0!==e&&t.vertexColors.push(new G(m));c.faces.push(r);c.faces.push(t)}else{r=new Sa;r.a=u[h++];r.b=u[h++];r.c=u[h++];g&&(g=u[h++],r.materialIndex=g);g=c.faces.length;if(e)for(e=0;e<I;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=
14440 [],f=0;3>f;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),c.faceVertexUvs[e][g].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]));if(z)for(e=0;3>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),r.vertexNormals.push(z);m&&(m=u[h++],r.color.setHex(w[m]));if(p)for(e=0;3>e;e++)m=u[h++],r.vertexColors.push(new G(w[m]));c.faces.push(r)}d=a;h=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(k=0,u=d.skinWeights.length;k<u;k+=h)c.skinWeights.push(new fa(d.skinWeights[k],1<h?d.skinWeights[k+
14441 1]:0,2<h?d.skinWeights[k+2]:0,3<h?d.skinWeights[k+3]:0));if(d.skinIndices)for(k=0,u=d.skinIndices.length;k<u;k+=h)c.skinIndices.push(new fa(d.skinIndices[k],1<h?d.skinIndices[k+1]:0,2<h?d.skinIndices[k+2]:0,3<h?d.skinIndices[k+3]:0));c.bones=d.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+
14442 ") should match.");k=a;u=k.scale;if(void 0!==k.morphTargets)for(d=0,h=k.morphTargets.length;d<h;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=k.morphTargets[d].name,c.morphTargets[d].vertices=[],B=c.morphTargets[d].vertices,w=k.morphTargets[d].vertices,I=0,p=w.length;I<p;I+=3)m=new n,m.x=w[I]*u,m.y=w[I+1]*u,m.z=w[I+2]*u,B.push(m);if(void 0!==k.morphColors&&0<k.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),u=c.faces,k=k.morphColors[0].colors,
14443 d=0,h=u.length;d<h;d++)u[d].color.fromArray(k,3*d);k=a;d=[];h=[];void 0!==k.animation&&h.push(k.animation);void 0!==k.animations&&(k.animations.length?h=h.concat(k.animations):h.push(k.animations));for(k=0;k<h.length;k++)(u=Da.parseAnimation(h[k],c.bones))&&d.push(u);c.morphTargets&&(h=Da.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(h));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};
14444 d=ec.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}}()});Object.assign(Pe.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ka(e.manager)).load(a,function(c){var g=null;try{g=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=g.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+
14445 a+". Use THREE.JSONLoader instead."):e.parse(g,b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&0!==a.images.length||void 0===b||b(e);return e},
14446 parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new ce,d=new be,e=0,f=a.length;e<f;e++){var g,h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Ma[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Ma[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new Ma[h.type](h.radius,h.segments,h.thetaStart,
14447 h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Ma[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Ma[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":g=new Ma[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,
14448 h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=new Ma[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Ma[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=new Ma[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=
14449 new Ma[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=new Ma[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}g.uuid=h.uuid;void 0!==h.name&&(g.name=h.name);b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==
14450 a){var d=new Gd;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=a[e];if("MultiMaterial"===g.type){for(var h=[],k=0;k<g.materials.length;k++)h.push(d.parse(g.materials[k]));c[g.uuid]=h}else c[g.uuid]=d.parse(g)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=Da.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return g.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}
14451 var d=this,e={};if(void 0!==a&&0<a.length){var f=new Zd(b),g=new Sc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],m=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(m)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&
14452 console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ba(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,ng));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],ff),h.wrapT=c(g.wrap[1],ff));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,gf));
14453 void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,gf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new K;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],c=0,e=a.length;c<e;c++){var f=a[c];void 0===d[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(d[f])}return b}void 0===
14454 d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}var g;switch(b.type){case "Scene":g=new ld;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new G(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Jb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ib(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new qa(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==
14455 b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=new Fb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new yd(b.color,b.intensity);break;case "DirectionalLight":g=new xd(b.color,b.intensity);break;case "PointLight":g=new vd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new zd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=
14456 new ud(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new sd(b.color,b.groundColor,b.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new nd(g,h):new la(g,h);break;case "LOD":g=new yc;break;case "Line":g=new sa(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new od(e(b.geometry),f(b.material));break;
14457 case "LineSegments":g=new Q(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Kb(e(b.geometry),f(b.material));break;case "Sprite":g=new xc(f(b.material));break;case "Group":g=new Ac;break;default:g=new z}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),
14458 void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=
14459 b.userData);if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var m=b[h];k=g.getObjectByProperty("uuid",m.object);void 0!==k&&g.addLevel(k,m.distance)}return g}}()});var ng={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},ff={RepeatWrapping:1E3,
14460 ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},gf={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(ua.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/
14461 a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.arcLengthDivisions);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=
14462 b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e-1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0<k)h=d-1;else{h=d;break}d=h;if(c[d]===f)return d/(e-1);g=c[d];return(d+(f-g)/(c[d+1]-g))/(e-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);
14463 return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new n,d=[],e=[],f=[],g=new n,h=new K,k,m;for(k=0;k<=a;k++)m=k/a,d[k]=this.getTangentAt(m),d[k].normalize();e[0]=new n;f[0]=new n;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),v=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));v<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-
14464 1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(Y.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(Y.clamp(e[0].dot(e[a]),-1,1)),c/=a,0<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}}});Qa.prototype=Object.create(ua.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isLineCurve=
14465 !0;Qa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);return b};Qa.prototype.getPointAt=function(a){return this.getPoint(a)};Qa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Vc.prototype=Object.assign(Object.create(ua.prototype),{constructor:Vc,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);
14466 a.equals(b)||this.curves.push(new Qa(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;
14467 for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){void 0===a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),
14468 c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},createPointsGeometry:function(a){a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){for(var b=new J,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new n(e.x,e.y,e.z||0))}return b}});Va.prototype=Object.create(ua.prototype);Va.prototype.constructor=Va;Va.prototype.isEllipseCurve=!0;Va.prototype.getPoint=
14469 function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)<Number.EPSILON;0>c;)c+=b;for(;c>b;)c-=b;c<Number.EPSILON&&(c=d?0:b);!0!==this.aClockwise||d||(c=c===b?-b:c-b);b=this.aStartAngle+a*c;a=this.aX+this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new C(a,e)};yb.prototype=Object.create(ua.prototype);yb.prototype.constructor=
14470 yb;yb.prototype.isSplineCurve=!0;yb.prototype.getPoint=function(a){var b=this.points,c=(b.length-1)*a;a=Math.floor(c);var c=c-a,d=b[0===a?a:a-1],e=b[a],f=b[a>b.length-2?b.length-1:a+1],b=b[a>b.length-3?b.length-1:a+2];return new C(Qe(c,d.x,e.x,f.x,b.x),Qe(c,d.y,e.y,f.y,b.y))};fc.prototype=Object.create(ua.prototype);fc.prototype.constructor=fc;fc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new C(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y))};gc.prototype=Object.create(ua.prototype);
14471 gc.prototype.constructor=gc;gc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new C(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y))};var te=Object.assign(Object.create(Vc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Qa(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,
14472 b,c,d){a=new gc(this.currentPoint.clone(),new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new fc(this.currentPoint.clone(),new C(a,b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new yb(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,
14473 b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,e,f,g,h){a=new Va(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)}});Wc.prototype=te;te.constructor=Wc;zb.prototype=Object.assign(Object.create(te),{constructor:zb,getPointsHoles:function(a){for(var b=
14474 [],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Object.assign(de.prototype,{moveTo:function(a,b){this.currentPath=new Wc;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,
14475 b,c,d,e,f){this.currentPath.bezierCurveTo(a,b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new zb;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,m=h.y-g.y;if(Math.abs(m)>Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;
14476 0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ia.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new zb,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var n=[],p=[],r=0,z;n[r]=void 0;p[r]=[];for(var t=0,y=f.length;t<y;t++)h=f[t],z=h.getPoints(),g=e(z),(g=a?!g:g)?(!l&&n[r]&&r++,n[r]={s:new zb,p:z},n[r].s.curves=h.curves,l&&r++,p[r]=[]):p[r].push({h:h,
14477 p:z[0]});if(!n[0])return c(f);if(1<n.length){t=!1;h=[];e=0;for(f=n.length;e<f;e++)k[e]=[];e=0;for(f=n.length;e<f;e++)for(g=p[e],l=0;l<g.length;l++){r=g[l];z=!0;for(y=0;y<n.length;y++)d(r.p,n[y].p)&&(e!==y&&h.push({froms:e,tos:y,hole:l}),z?(z=!1,k[y].push(r)):t=!0);z&&k[e].push(r)}0<h.length&&(t||(p=k))}t=0;for(e=n.length;t<e;t++)for(k=n[t].s,m.push(k),h=p[t],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return m}});Object.assign(ee.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=
14478 100);void 0===c&&(c=4);var d=this.data;a=String(a).split("");var e=b/d.resolution,f=(d.boundingBox.yMax-d.boundingBox.yMin+d.underlineThickness)*e,g=0,h=0;b=[];for(var k=0;k<a.length;k++){var m=a[k];if("\n"===m)g=0,h-=f;else{var l;l=e;var n=g,p=h;if(m=d.glyphs[m]||d.glyphs["?"]){var r=new de,z=[],t,y,x,u,B,w,C,G;if(m.o)for(var D=m._cachedOutline||(m._cachedOutline=m.o.split(" ")),E=0,J=D.length;E<J;)switch(D[E++]){case "m":t=D[E++]*l+n;y=D[E++]*l+p;r.moveTo(t,y);break;case "l":t=D[E++]*l+n;y=D[E++]*
14479 l+p;r.lineTo(t,y);break;case "q":t=D[E++]*l+n;y=D[E++]*l+p;B=D[E++]*l+n;w=D[E++]*l+p;r.quadraticCurveTo(B,w,t,y);if(u=z[z.length-1]){x=u.x;u=u.y;for(var F=1;F<=c;F++){var K=F/c;wb(K,x,B,t);wb(K,u,w,y)}}break;case "b":if(t=D[E++]*l+n,y=D[E++]*l+p,B=D[E++]*l+n,w=D[E++]*l+p,C=D[E++]*l+n,G=D[E++]*l+p,r.bezierCurveTo(B,w,C,G,t,y),u=z[z.length-1])for(x=u.x,u=u.y,F=1;F<=c;F++)K=F/c,xb(K,x,B,C,t),xb(K,u,w,G,y)}l={offsetX:m.ha*l,path:r}}else l=void 0;g+=l.offsetX;b.push(l.path)}}c=[];d=0;for(a=b.length;d<
14480 a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Re.prototype,{load:function(a,b,c,d){var e=this;(new Ka(this.manager)).load(a,function(a){var c;try{c=JSON.parse(a)}catch(d){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new ee(a)}});var Nd,he={getContext:function(){void 0===Nd&&(Nd=new (window.AudioContext||window.webkitAudioContext));
14481 return Nd},setContext:function(a){Nd=a}};Object.assign(fe.prototype,{load:function(a,b,c,d){var e=new Ka(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){he.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Se.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new K,m=new K;return function(l){if(a!==this||b!==l.focus||c!==l.fov||d!==l.aspect*this.aspect||e!==l.near||f!==l.far||g!==l.zoom||h!==this.eyeSep){a=this;b=l.focus;c=l.fov;d=l.aspect*this.aspect;e=
14482 l.near;f=l.far;g=l.zoom;var n=l.projectionMatrix.clone();h=this.eyeSep/2;var p=h*e/b,r=e*Math.tan(Y.DEG2RAD*c*.5)/g,z,t;m.elements[12]=-h;k.elements[12]=h;z=-r*d+p;t=r*d+p;n.elements[0]=2*e/(t-z);n.elements[8]=(t+z)/(t-z);this.cameraL.projectionMatrix.copy(n);z=-r*d-p;t=r*d-p;n.elements[0]=2*e/(t-z);n.elements[8]=(t+z)/(t-z);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(l.matrixWorld).multiply(m);this.cameraR.matrixWorld.copy(l.matrixWorld).multiply(k)}}()});Hd.prototype=Object.create(z.prototype);
14483 Hd.prototype.constructor=Hd;ge.prototype=Object.assign(Object.create(z.prototype),{constructor:ge,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination);
14484 this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new n,b=new oa,c=new n,d=new n;return function(e){z.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,this.context.currentTime),
14485 e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,
14486 f.z))}}()});hc.prototype=Object.assign(Object.create(z.prototype),{constructor:hc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
14487 else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,this.startTime);a.start(0,this.startTime);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
14488 else return this.source.stop(),this.startTime=0,this.isPlaying=!1,this},connect:function(){if(0<this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-
14489 1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
14490 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=
14491 a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});ie.prototype=Object.assign(Object.create(hc.prototype),{constructor:ie,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=
14492 a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new n;return function(b){z.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(je.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);
14493 return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Object.assign(ke.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize,e=a*d+d,f=this.cumulativeWeight;if(0===f){for(f=0;f!==d;++f)c[e+f]=c[f];f=b}else f+=b,this._mixBufferRegion(c,e,0,b/f,d);this.cumulativeWeight=f},apply:function(a){var b=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&
14494 this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){oa.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=
14495 1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Te.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,
14496 c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(ha,{Composite:Te,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new ha.Composite(a,b,c):new ha(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+"$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+
14497 c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;
14498 if(a.skeleton){var c=function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};if(c=d(a.children))return c}return null}});Object.assign(ha.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,
14499 NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.node[this.propertyName]=
14500 a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=
14501 a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=
14502 this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=ha.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",
14503 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.",
14504 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.",
14505 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.",
14506 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: "+
14507 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(ha.prototype,{_getValue_unbound:ha.prototype.getValue,_setValue_unbound:ha.prototype.setValue});Object.assign(Ue.prototype,{isAnimationObjectGroup:!0,add:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._paths,g=this._parsedPaths,h=this._bindings,k=h.length,m=0,l=arguments.length;m!==l;++m){var n=
14508 arguments[m],p=n.uuid,r=e[p];if(void 0===r){r=c++;e[p]=r;b.push(n);for(var p=0,z=k;p!==z;++p)h[p].push(new ha(n,f[p],g[p]))}else if(r<d){var t=--d,z=b[t];e[z.uuid]=r;b[r]=z;e[p]=t;b[t]=n;p=0;for(z=k;p!==z;++p){var y=h[p],x=y[r];y[r]=y[t];void 0===x&&(x=new ha(n,f[p],g[p]));y[t]=x}}else void 0!==b[r]&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=d},remove:function(a){for(var b=
14509 this._objects,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=arguments[g],m=k.uuid,l=d[m];if(void 0!==l&&l>=c){var n=c++,p=b[n];d[p.uuid]=l;b[l]=p;d[m]=n;b[n]=k;k=0;for(m=f;k!==m;++k){var p=e[k],r=p[l];p[l]=p[n];p[n]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,n=e[l];
14510 if(void 0!==n)if(delete e[l],n<d){var l=--d,v=b[l],p=--c,r=b[p];e[v.uuid]=n;b[n]=v;e[r.uuid]=l;b[l]=r;b.pop();v=0;for(r=g;v!==r;++v){var z=f[v],t=z[p];z[n]=z[l];z[l]=t;z.pop()}}else for(p=--c,r=b[p],e[r.uuid]=n,b[n]=r,b.pop(),v=0,r=g;v!==r;++v)z=f[v],z[n]=z[p],z.pop()}this.nCachedObjects_=d},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;
14511 c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new ha(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(Ve.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=
14512 !1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?
14513 a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=
14514 null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,
14515 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||
14516 this._mixer._root},_update:function(a,b,c,d){if(this.enabled){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;for(var e=this._propertyBindings,f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}}else this._updateWeight(a)},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],
14517 b=b*d;a>c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===
14518 d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?
14519 c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,
14520 b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(We.prototype,xa.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var n=d[k],v=n.name,p=l[v];if(void 0===
14521 p){p=f[k];if(void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,h,v));continue}p=new ke(ha.create(c,v,b&&b._propertyBindings[k].binding.parsedPath),n.ValueTypeName,n.getValueSize());++p.referenceCount;this._addInactiveBinding(p,h,v)}f[k]=p;g[k].resultBuffer=p.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,
14522 c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=
14523 0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},
14524 _addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var b=a._clip.uuid,c=this._actionsByClip,d=c[b],e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;
14525 f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=
14526 this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;
14527 delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=--this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Tc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),
14528 c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Da.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===
14529 e&&(e=g._clip)}if(null===e)return null;e=new Ve(this,e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?Da.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=
14530 0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g)b[g]._update(d,a,e,f);a=this._bindings;b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=
14531 g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,
14532 b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Id.prototype.clone=function(){return new Id(void 0===this.value.clone?this.value:this.value.clone())};le.prototype=Object.assign(Object.create(E.prototype),{constructor:le,isInstancedBufferGeometry:!0,addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})},copy:function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,b[c].clone());a=a.groups;c=0;for(b=
14533 a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this}});Object.defineProperties(me.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(me.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+
14534 this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+
14535 1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});Object.defineProperty(ic.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ic.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
14536 this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=
14537 a;return this}});ne.prototype=Object.assign(Object.create(ic.prototype),{constructor:ne,isInstancedInterleavedBuffer:!0,copy:function(a){ic.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});oe.prototype=Object.assign(Object.create(Z.prototype),{constructor:oe,isInstancedBufferAttribute:!0,copy:function(a){Z.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(Xe.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,
14538 b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];pe(a,this,c,b);c.sort(Ye);return c},intersectObjects:function(a,
14539 b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)pe(a[d],this,c,b);c.sort(Ye);return c}});Object.assign(Ze.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=
14540 0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){var b=("undefined"===typeof performance?Date:performance).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign($e.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-
14541 1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(Y.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(af.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*
14542 a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ta.prototype=Object.create(la.prototype);ta.prototype.constructor=ta;ta.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};ta.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<
14543 g;f++){var h=e.morphTargets[f].name.match(b);if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};ta.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ta.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ta.prototype.setAnimationFPS=
14544 function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ta.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};ta.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ta.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ta.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ta.prototype.getAnimationDuration=
14545 function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ta.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};ta.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ta.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b<c;b++){var d=this.animationsList[b];if(d.active){var e=d.duration/d.length;d.time+=d.direction*a;if(d.mirroredLoop){if(d.time>
14546 d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+Y.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==
14547 d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};Xc.prototype=Object.create(z.prototype);Xc.prototype.constructor=Xc;Xc.prototype.isImmediateRenderObject=!0;Yc.prototype=Object.create(Q.prototype);Yc.prototype.constructor=Yc;Yc.prototype.update=function(){var a=new n,b=new n,c=new Ba;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);
14548 var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,n=k.length;l<n;l++)for(var v=k[l],p=0,r=v.vertexNormals.length;p<r;p++){var z=v.vertexNormals[p];a.copy(h[v[d[p]]]).applyMatrix4(e);b.copy(z).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&g.isBufferGeometry)for(d=g.attributes.position,h=g.attributes.normal,p=g=0,r=d.count;p<
14549 r;p++)a.set(d.getX(p),d.getY(p),d.getZ(p)).applyMatrix4(e),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0}}();jc.prototype=Object.create(z.prototype);jc.prototype.constructor=jc;jc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};jc.prototype.update=function(){var a=new n,b=new n;return function(){this.light.updateMatrixWorld();var c=
14550 this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));this.cone.material.color.copy(this.light.color)}}();kc.prototype=Object.create(Q.prototype);kc.prototype.constructor=kc;kc.prototype.onBeforeRender=function(){var a=new n,b=new K,c=new K;return function(){var d=this.bones,e=this.geometry,f=e.getAttribute("position");c.getInverse(this.root.matrixWorld);
14551 for(var g=0,h=0;g<d.length;g++){var k=d[g];k.parent&&k.parent.isBone&&(b.multiplyMatrices(c,k.matrixWorld),a.setFromMatrixPosition(b),f.setXYZ(h,a.x,a.y,a.z),b.multiplyMatrices(c,k.parent.matrixWorld),a.setFromMatrixPosition(b),f.setXYZ(h+1,a.x,a.y,a.z),h+=2)}e.getAttribute("position").needsUpdate=!0}}();lc.prototype=Object.create(la.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};lc.prototype.update=function(){this.material.color.copy(this.light.color)};
14552 mc.prototype=Object.create(z.prototype);mc.prototype.constructor=mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=function(){var a=this.children[0];a.material.color.copy(this.light.color);var b=.5*this.light.width,c=.5*this.light.height,a=a.geometry.attributes.position,d=a.array;d[0]=b;d[1]=-c;d[2]=0;d[3]=b;d[4]=c;d[5]=0;d[6]=-b;d[7]=c;d[8]=0;d[9]=-b;d[10]=-c;d[11]=0;d[12]=b;d[13]=-c;d[14]=0;a.needsUpdate=!0};nc.prototype=
14553 Object.create(z.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};nc.prototype.update=function(){var a=new n,b=new G,c=new G;return function(){var d=this.children[0],e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());e.needsUpdate=
14554 !0}}();Zc.prototype=Object.create(Q.prototype);Zc.prototype.constructor=Zc;Jd.prototype=Object.create(Q.prototype);Jd.prototype.constructor=Jd;$c.prototype=Object.create(Q.prototype);$c.prototype.constructor=$c;$c.prototype.update=function(){var a=new n,b=new n,c=new Ba;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<
14555 l;k++){var n=f[k],v=n.normal;a.copy(g[n.a]).add(g[n.b]).add(g[n.c]).divideScalar(3).applyMatrix4(d);b.copy(v).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();oc.prototype=Object.create(z.prototype);oc.prototype.constructor=oc;oc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};oc.prototype.update=function(){var a=
14556 new n,b=new n,c=new n;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,a);var d=this.children[0],e=this.children[1];d.lookAt(c);d.material.color.copy(this.light.color);e.lookAt(c);e.scale.z=c.length()}}();ad.prototype=Object.create(Q.prototype);ad.prototype.constructor=ad;ad.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),h=0,k=a.length;h<
14557 k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new n,e=new Na;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",0,1,-1);b.getAttribute("position").needsUpdate=
14558 !0}}();Ab.prototype=Object.create(Q.prototype);Ab.prototype.constructor=Ab;Ab.prototype.update=function(){var a=new Ra;return function(b){void 0!==b&&console.warn("THREE.BoxHelper: .update() has no longer arguments.");void 0!==this.object&&a.setFromObject(this.object);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;
14559 e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();Ab.prototype.setFromObject=function(a){this.object=a;this.update();return this};var Kd,qe;Bb.prototype=Object.create(z.prototype);Bb.prototype.constructor=Bb;Bb.prototype.setDirection=function(){var a=new n,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,
14560 b))}}();Bb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Bb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};Ld.prototype=Object.create(Q.prototype);Ld.prototype.constructor=Ld;var Od=new n,ue=new re,ve=new re,we=new re;La.prototype=Object.create(ua.prototype);La.prototype.constructor=
14561 La;La.prototype.getPoint=function(a){var b=this.points,c=b.length;a*=c-(this.closed?0:1);var d=Math.floor(a);a-=d;this.closed?d+=0<d?0:(Math.floor(Math.abs(d)/b.length)+1)*b.length:0===a&&d===c-1&&(d=c-2,a=1);var e,f,g;this.closed||0<d?e=b[(d-1)%c]:(Od.subVectors(b[0],b[1]).add(b[0]),e=Od);f=b[d%c];g=b[(d+1)%c];this.closed||d+2<c?b=b[(d+2)%c]:(Od.subVectors(b[c-1],b[c-2]).add(b[c-1]),b=Od);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var h="chordal"===this.type?.5:.25,
14562 c=Math.pow(e.distanceToSquared(f),h),d=Math.pow(f.distanceToSquared(g),h),h=Math.pow(g.distanceToSquared(b),h);1E-4>d&&(d=1);1E-4>c&&(c=d);1E-4>h&&(h=d);ue.initNonuniformCatmullRom(e.x,f.x,g.x,b.x,c,d,h);ve.initNonuniformCatmullRom(e.y,f.y,g.y,b.y,c,d,h);we.initNonuniformCatmullRom(e.z,f.z,g.z,b.z,c,d,h)}else"catmullrom"===this.type&&(c=void 0!==this.tension?this.tension:.5,ue.initCatmullRom(e.x,f.x,g.x,b.x,c),ve.initCatmullRom(e.y,f.y,g.y,b.y,c),we.initCatmullRom(e.z,f.z,g.z,b.z,c));return new n(ue.calc(a),
14563 ve.calc(a),we.calc(a))};bd.prototype=Object.create(ua.prototype);bd.prototype.constructor=bd;bd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new n(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y),xb(a,b.z,c.z,d.z,e.z))};cd.prototype=Object.create(ua.prototype);cd.prototype.constructor=cd;cd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new n(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y),wb(a,b.z,c.z,d.z))};dd.prototype=Object.create(ua.prototype);dd.prototype.constructor=
14564 dd;dd.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=new n;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b};Md.prototype=Object.create(Va.prototype);Md.prototype.constructor=Md;ua.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(ua.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};cf.prototype=Object.create(La.prototype);df.prototype=Object.create(La.prototype);se.prototype=Object.create(La.prototype);
14565 Object.assign(se.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(a){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(a){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});Zc.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};kc.prototype.update=
14566 function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(fd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");
14567 return this.getSize(a)}});Object.assign(Ra.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");
14568 return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});Hb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Y.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(Ba.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
14569 return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,
14570 b,c){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(K.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;return function(){void 0===a&&(a=new n);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");
14571 return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");
14572 return a.applyMatrix4(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},
14573 rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},
14574 applyToVector3Array:function(a,b,c){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Aa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};oa.prototype.multiplyVector3=
14575 function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(kb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");
14576 return this.intersectsSphere(a)}});Object.assign(zb.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new cb(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Xb(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
14577 b,c)}});Object.assign(n.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},
14578 getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},fromAttribute:function(a,
14579 b,c){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(fa.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});J.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(z.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
14580 return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(z.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");
14581 this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(yc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(zc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
14582 set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(ua.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});qa.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");
14583 void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(na.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");
14584 this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");
14585 this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");this.shadow.bias=a}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");
14586 this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(Z.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(E.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
14587 b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});
14588 Object.defineProperties(E.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});Object.defineProperties(Id.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");
14589 return this}}});Object.defineProperties(U.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new G}}});Object.defineProperties(Ja.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});
14590 Object.defineProperties(ra.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Xd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},
14591 supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");
14592 return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},
14593 supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");
14594 return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});
14595 Object.defineProperties(Xd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");
14596 this.shadowMap.cullFace=a}}});Object.defineProperties(Ie.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Cb.prototype,{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");
14597 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=
14598 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=
14599 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.");
14600 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},
14601 set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});hc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new fe).load(a,function(a){b.setBuffer(a)});return this};je.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Db;l.WebGLRenderTarget=
14602 Cb;l.WebGLRenderer=Xd;l.ShaderLib=$a;l.UniformsLib=R;l.UniformsUtils=Ca;l.ShaderChunk=X;l.FogExp2=Ib;l.Fog=Jb;l.Scene=ld;l.LensFlare=Yd;l.Sprite=xc;l.LOD=yc;l.SkinnedMesh=nd;l.Skeleton=zc;l.Bone=md;l.Mesh=la;l.LineSegments=Q;l.LineLoop=od;l.Line=sa;l.Points=Kb;l.Group=Ac;l.VideoTexture=pd;l.DataTexture=db;l.CompressedTexture=Lb;l.CubeTexture=Xa;l.CanvasTexture=qd;l.DepthTexture=Bc;l.Texture=ba;l.CompressedTextureLoader=Oe;l.DataTextureLoader=$d;l.CubeTextureLoader=ae;l.TextureLoader=rd;l.ObjectLoader=
14603 Pe;l.MaterialLoader=Gd;l.BufferGeometryLoader=be;l.DefaultLoadingManager=va;l.LoadingManager=Zd;l.JSONLoader=ce;l.ImageLoader=Sc;l.FontLoader=Re;l.FileLoader=Ka;l.Loader=ec;l.Cache=ed;l.AudioLoader=fe;l.SpotLightShadow=td;l.SpotLight=ud;l.PointLight=vd;l.RectAreaLight=zd;l.HemisphereLight=sd;l.DirectionalLightShadow=wd;l.DirectionalLight=xd;l.AmbientLight=yd;l.LightShadow=tb;l.Light=na;l.StereoCamera=Se;l.PerspectiveCamera=qa;l.OrthographicCamera=Fb;l.CubeCamera=Hd;l.ArrayCamera=kd;l.Camera=Na;l.AudioListener=
14604 ge;l.PositionalAudio=ie;l.AudioContext=he;l.AudioAnalyser=je;l.Audio=hc;l.VectorKeyframeTrack=cc;l.StringKeyframeTrack=Dd;l.QuaternionKeyframeTrack=Uc;l.NumberKeyframeTrack=dc;l.ColorKeyframeTrack=Fd;l.BooleanKeyframeTrack=Ed;l.PropertyMixer=ke;l.PropertyBinding=ha;l.KeyframeTrack=vb;l.AnimationUtils=ia;l.AnimationObjectGroup=Ue;l.AnimationMixer=We;l.AnimationClip=Da;l.Uniform=Id;l.InstancedBufferGeometry=le;l.BufferGeometry=E;l.GeometryIdCount=function(){return Rd++};l.Geometry=J;l.InterleavedBufferAttribute=
14605 me;l.InstancedInterleavedBuffer=ne;l.InterleavedBuffer=ic;l.InstancedBufferAttribute=oe;l.Face3=Sa;l.Object3D=z;l.Raycaster=Xe;l.Layers=Qd;l.EventDispatcher=xa;l.Clock=Ze;l.QuaternionLinearInterpolant=Cd;l.LinearInterpolant=Tc;l.DiscreteInterpolant=Bd;l.CubicInterpolant=Ad;l.Interpolant=wa;l.Triangle=Ta;l.Math=Y;l.Spherical=$e;l.Cylindrical=af;l.Plane=Aa;l.Frustum=gd;l.Sphere=Ea;l.Ray=kb;l.Matrix4=K;l.Matrix3=Ba;l.Box3=Ra;l.Box2=fd;l.Line3=Hb;l.Euler=ab;l.Vector4=fa;l.Vector3=n;l.Vector2=C;l.Quaternion=
14606 oa;l.Color=G;l.MorphBlendMesh=ta;l.ImmediateRenderObject=Xc;l.VertexNormalsHelper=Yc;l.SpotLightHelper=jc;l.SkeletonHelper=kc;l.PointLightHelper=lc;l.RectAreaLightHelper=mc;l.HemisphereLightHelper=nc;l.GridHelper=Zc;l.PolarGridHelper=Jd;l.FaceNormalsHelper=$c;l.DirectionalLightHelper=oc;l.CameraHelper=ad;l.BoxHelper=Ab;l.ArrowHelper=Bb;l.AxisHelper=Ld;l.CatmullRomCurve3=La;l.CubicBezierCurve3=bd;l.QuadraticBezierCurve3=cd;l.LineCurve3=dd;l.ArcCurve=Md;l.EllipseCurve=Va;l.SplineCurve=yb;l.CubicBezierCurve=
14607 fc;l.QuadraticBezierCurve=gc;l.LineCurve=Qa;l.Shape=zb;l.Path=Wc;l.ShapePath=de;l.Font=ee;l.CurvePath=Vc;l.Curve=ua;l.ShapeUtils=Ia;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Ac,d=0,e=b.length;d<e;d++)c.add(new la(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){a.applyMatrix((new K).getInverse(c.matrixWorld));b.remove(a);c.add(a)}};l.WireframeGeometry=Mb;l.ParametricGeometry=Cc;l.ParametricBufferGeometry=
14608 Nb;l.TetrahedronGeometry=Ec;l.TetrahedronBufferGeometry=Ob;l.OctahedronGeometry=Fc;l.OctahedronBufferGeometry=lb;l.IcosahedronGeometry=Gc;l.IcosahedronBufferGeometry=Pb;l.DodecahedronGeometry=Hc;l.DodecahedronBufferGeometry=Qb;l.PolyhedronGeometry=Dc;l.PolyhedronBufferGeometry=za;l.TubeGeometry=Ic;l.TubeBufferGeometry=Rb;l.TorusKnotGeometry=Jc;l.TorusKnotBufferGeometry=Sb;l.TorusGeometry=Kc;l.TorusBufferGeometry=Tb;l.TextGeometry=Lc;l.TextBufferGeometry=Ub;l.SphereGeometry=Mc;l.SphereBufferGeometry=
14609 mb;l.RingGeometry=Nc;l.RingBufferGeometry=Vb;l.PlaneGeometry=vc;l.PlaneBufferGeometry=jb;l.LatheGeometry=Oc;l.LatheBufferGeometry=Wb;l.ShapeGeometry=Xb;l.ShapeBufferGeometry=Yb;l.ExtrudeGeometry=cb;l.ExtrudeBufferGeometry=Ga;l.EdgesGeometry=Zb;l.ConeGeometry=Pc;l.ConeBufferGeometry=Qc;l.CylinderGeometry=nb;l.CylinderBufferGeometry=Ua;l.CircleGeometry=Rc;l.CircleBufferGeometry=$b;l.BoxGeometry=Gb;l.BoxBufferGeometry=ib;l.ShadowMaterial=ac;l.SpriteMaterial=bb;l.RawShaderMaterial=bc;l.ShaderMaterial=
14610 ra;l.PointsMaterial=Fa;l.MeshPhysicalMaterial=ob;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Ja;l.MeshToonMaterial=pb;l.MeshNormalMaterial=qb;l.MeshLambertMaterial=rb;l.MeshDepthMaterial=Za;l.MeshBasicMaterial=ya;l.LineDashedMaterial=sb;l.LineBasicMaterial=ea;l.Material=U;l.Float64BufferAttribute=uc;l.Float32BufferAttribute=B;l.Uint32BufferAttribute=hb;l.Int32BufferAttribute=tc;l.Uint16BufferAttribute=gb;l.Int16BufferAttribute=sc;l.Uint8ClampedBufferAttribute=rc;l.Uint8BufferAttribute=qc;l.Int8BufferAttribute=
14611 pc;l.BufferAttribute=Z;l.REVISION="86";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=
14612 100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=
14613 0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=
14614 1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=
14615 1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=2001;l.RGBA_S3TC_DXT1_Format=2002;l.RGBA_S3TC_DXT3_Format=2003;l.RGBA_S3TC_DXT5_Format=2004;l.RGB_PVRTC_4BPPV1_Format=2100;l.RGB_PVRTC_2BPPV1_Format=2101;l.RGBA_PVRTC_4BPPV1_Format=2102;l.RGBA_PVRTC_2BPPV1_Format=2103;l.RGB_ETC1_Format=2151;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=
14616 2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=Gb;l.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Sa(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=
14617 function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Kb(a,b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");
14618 return new xc(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Kb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Fa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Fa(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");
14619 return new Fa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new n(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new Z(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new pc(a,b)};l.Uint8Attribute=
14620 function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new qc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new rc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new sc(a,b)};l.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");
14621 return new gb(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new tc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new hb(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new B(a,b)};l.Float64Attribute=
14622 function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new uc(a,b)};l.ClosedSplineCurve3=cf;l.SplineCurve3=df;l.Spline=se;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Ab(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new Q(new Zb(a.geometry),new ea({color:void 0!==
14623 b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new Q(new Mb(a.geometry),new ea({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ka(a)};l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new $d(a)};l.GeometryUtils={merge:function(a,b,
14624 c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var d;b.isMesh&&(b.matrixAutoUpdate&&b.updateMatrix(),d=b.matrix,b=b.geometry);a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};l.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");
14625 var e=new rd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var e=new ae;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};
14626 l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};l.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");
14627 this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(l,"__esModule",{value:!0})});
14628
14629 },{}],181:[function(require,module,exports){
14630 'use strict';
14631
14632 module.exports = TinyQueue;
14633
14634 function TinyQueue(data, compare) {
14635     if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
14636
14637     this.data = data || [];
14638     this.length = this.data.length;
14639     this.compare = compare || defaultCompare;
14640
14641     if (this.length > 0) {
14642         for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
14643     }
14644 }
14645
14646 function defaultCompare(a, b) {
14647     return a < b ? -1 : a > b ? 1 : 0;
14648 }
14649
14650 TinyQueue.prototype = {
14651
14652     push: function (item) {
14653         this.data.push(item);
14654         this.length++;
14655         this._up(this.length - 1);
14656     },
14657
14658     pop: function () {
14659         if (this.length === 0) return undefined;
14660         var top = this.data[0];
14661         this.length--;
14662         if (this.length > 0) {
14663             this.data[0] = this.data[this.length];
14664             this._down(0);
14665         }
14666         this.data.pop();
14667         return top;
14668     },
14669
14670     peek: function () {
14671         return this.data[0];
14672     },
14673
14674     _up: function (pos) {
14675         var data = this.data;
14676         var compare = this.compare;
14677         var item = data[pos];
14678
14679         while (pos > 0) {
14680             var parent = (pos - 1) >> 1;
14681             var current = data[parent];
14682             if (compare(item, current) >= 0) break;
14683             data[pos] = current;
14684             pos = parent;
14685         }
14686
14687         data[pos] = item;
14688     },
14689
14690     _down: function (pos) {
14691         var data = this.data;
14692         var compare = this.compare;
14693         var len = this.length;
14694         var halfLen = len >> 1;
14695         var item = data[pos];
14696
14697         while (pos < halfLen) {
14698             var left = (pos << 1) + 1;
14699             var right = left + 1;
14700             var best = data[left];
14701
14702             if (right < len && compare(data[right], best) < 0) {
14703                 left = right;
14704                 best = data[right];
14705             }
14706             if (compare(best, item) >= 0) break;
14707
14708             data[pos] = best;
14709             pos = left;
14710         }
14711
14712         data[pos] = item;
14713     }
14714 };
14715
14716 },{}],182:[function(require,module,exports){
14717 //     Underscore.js 1.8.3
14718 //     http://underscorejs.org
14719 //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14720 //     Underscore may be freely distributed under the MIT license.
14721
14722 (function() {
14723
14724   // Baseline setup
14725   // --------------
14726
14727   // Establish the root object, `window` in the browser, or `exports` on the server.
14728   var root = this;
14729
14730   // Save the previous value of the `_` variable.
14731   var previousUnderscore = root._;
14732
14733   // Save bytes in the minified (but not gzipped) version:
14734   var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
14735
14736   // Create quick reference variables for speed access to core prototypes.
14737   var
14738     push             = ArrayProto.push,
14739     slice            = ArrayProto.slice,
14740     toString         = ObjProto.toString,
14741     hasOwnProperty   = ObjProto.hasOwnProperty;
14742
14743   // All **ECMAScript 5** native function implementations that we hope to use
14744   // are declared here.
14745   var
14746     nativeIsArray      = Array.isArray,
14747     nativeKeys         = Object.keys,
14748     nativeBind         = FuncProto.bind,
14749     nativeCreate       = Object.create;
14750
14751   // Naked function reference for surrogate-prototype-swapping.
14752   var Ctor = function(){};
14753
14754   // Create a safe reference to the Underscore object for use below.
14755   var _ = function(obj) {
14756     if (obj instanceof _) return obj;
14757     if (!(this instanceof _)) return new _(obj);
14758     this._wrapped = obj;
14759   };
14760
14761   // Export the Underscore object for **Node.js**, with
14762   // backwards-compatibility for the old `require()` API. If we're in
14763   // the browser, add `_` as a global object.
14764   if (typeof exports !== 'undefined') {
14765     if (typeof module !== 'undefined' && module.exports) {
14766       exports = module.exports = _;
14767     }
14768     exports._ = _;
14769   } else {
14770     root._ = _;
14771   }
14772
14773   // Current version.
14774   _.VERSION = '1.8.3';
14775
14776   // Internal function that returns an efficient (for current engines) version
14777   // of the passed-in callback, to be repeatedly applied in other Underscore
14778   // functions.
14779   var optimizeCb = function(func, context, argCount) {
14780     if (context === void 0) return func;
14781     switch (argCount == null ? 3 : argCount) {
14782       case 1: return function(value) {
14783         return func.call(context, value);
14784       };
14785       case 2: return function(value, other) {
14786         return func.call(context, value, other);
14787       };
14788       case 3: return function(value, index, collection) {
14789         return func.call(context, value, index, collection);
14790       };
14791       case 4: return function(accumulator, value, index, collection) {
14792         return func.call(context, accumulator, value, index, collection);
14793       };
14794     }
14795     return function() {
14796       return func.apply(context, arguments);
14797     };
14798   };
14799
14800   // A mostly-internal function to generate callbacks that can be applied
14801   // to each element in a collection, returning the desired result — either
14802   // identity, an arbitrary callback, a property matcher, or a property accessor.
14803   var cb = function(value, context, argCount) {
14804     if (value == null) return _.identity;
14805     if (_.isFunction(value)) return optimizeCb(value, context, argCount);
14806     if (_.isObject(value)) return _.matcher(value);
14807     return _.property(value);
14808   };
14809   _.iteratee = function(value, context) {
14810     return cb(value, context, Infinity);
14811   };
14812
14813   // An internal function for creating assigner functions.
14814   var createAssigner = function(keysFunc, undefinedOnly) {
14815     return function(obj) {
14816       var length = arguments.length;
14817       if (length < 2 || obj == null) return obj;
14818       for (var index = 1; index < length; index++) {
14819         var source = arguments[index],
14820             keys = keysFunc(source),
14821             l = keys.length;
14822         for (var i = 0; i < l; i++) {
14823           var key = keys[i];
14824           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
14825         }
14826       }
14827       return obj;
14828     };
14829   };
14830
14831   // An internal function for creating a new object that inherits from another.
14832   var baseCreate = function(prototype) {
14833     if (!_.isObject(prototype)) return {};
14834     if (nativeCreate) return nativeCreate(prototype);
14835     Ctor.prototype = prototype;
14836     var result = new Ctor;
14837     Ctor.prototype = null;
14838     return result;
14839   };
14840
14841   var property = function(key) {
14842     return function(obj) {
14843       return obj == null ? void 0 : obj[key];
14844     };
14845   };
14846
14847   // Helper for collection methods to determine whether a collection
14848   // should be iterated as an array or as an object
14849   // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
14850   // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
14851   var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
14852   var getLength = property('length');
14853   var isArrayLike = function(collection) {
14854     var length = getLength(collection);
14855     return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
14856   };
14857
14858   // Collection Functions
14859   // --------------------
14860
14861   // The cornerstone, an `each` implementation, aka `forEach`.
14862   // Handles raw objects in addition to array-likes. Treats all
14863   // sparse array-likes as if they were dense.
14864   _.each = _.forEach = function(obj, iteratee, context) {
14865     iteratee = optimizeCb(iteratee, context);
14866     var i, length;
14867     if (isArrayLike(obj)) {
14868       for (i = 0, length = obj.length; i < length; i++) {
14869         iteratee(obj[i], i, obj);
14870       }
14871     } else {
14872       var keys = _.keys(obj);
14873       for (i = 0, length = keys.length; i < length; i++) {
14874         iteratee(obj[keys[i]], keys[i], obj);
14875       }
14876     }
14877     return obj;
14878   };
14879
14880   // Return the results of applying the iteratee to each element.
14881   _.map = _.collect = function(obj, iteratee, context) {
14882     iteratee = cb(iteratee, context);
14883     var keys = !isArrayLike(obj) && _.keys(obj),
14884         length = (keys || obj).length,
14885         results = Array(length);
14886     for (var index = 0; index < length; index++) {
14887       var currentKey = keys ? keys[index] : index;
14888       results[index] = iteratee(obj[currentKey], currentKey, obj);
14889     }
14890     return results;
14891   };
14892
14893   // Create a reducing function iterating left or right.
14894   function createReduce(dir) {
14895     // Optimized iterator function as using arguments.length
14896     // in the main function will deoptimize the, see #1991.
14897     function iterator(obj, iteratee, memo, keys, index, length) {
14898       for (; index >= 0 && index < length; index += dir) {
14899         var currentKey = keys ? keys[index] : index;
14900         memo = iteratee(memo, obj[currentKey], currentKey, obj);
14901       }
14902       return memo;
14903     }
14904
14905     return function(obj, iteratee, memo, context) {
14906       iteratee = optimizeCb(iteratee, context, 4);
14907       var keys = !isArrayLike(obj) && _.keys(obj),
14908           length = (keys || obj).length,
14909           index = dir > 0 ? 0 : length - 1;
14910       // Determine the initial value if none is provided.
14911       if (arguments.length < 3) {
14912         memo = obj[keys ? keys[index] : index];
14913         index += dir;
14914       }
14915       return iterator(obj, iteratee, memo, keys, index, length);
14916     };
14917   }
14918
14919   // **Reduce** builds up a single result from a list of values, aka `inject`,
14920   // or `foldl`.
14921   _.reduce = _.foldl = _.inject = createReduce(1);
14922
14923   // The right-associative version of reduce, also known as `foldr`.
14924   _.reduceRight = _.foldr = createReduce(-1);
14925
14926   // Return the first value which passes a truth test. Aliased as `detect`.
14927   _.find = _.detect = function(obj, predicate, context) {
14928     var key;
14929     if (isArrayLike(obj)) {
14930       key = _.findIndex(obj, predicate, context);
14931     } else {
14932       key = _.findKey(obj, predicate, context);
14933     }
14934     if (key !== void 0 && key !== -1) return obj[key];
14935   };
14936
14937   // Return all the elements that pass a truth test.
14938   // Aliased as `select`.
14939   _.filter = _.select = function(obj, predicate, context) {
14940     var results = [];
14941     predicate = cb(predicate, context);
14942     _.each(obj, function(value, index, list) {
14943       if (predicate(value, index, list)) results.push(value);
14944     });
14945     return results;
14946   };
14947
14948   // Return all the elements for which a truth test fails.
14949   _.reject = function(obj, predicate, context) {
14950     return _.filter(obj, _.negate(cb(predicate)), context);
14951   };
14952
14953   // Determine whether all of the elements match a truth test.
14954   // Aliased as `all`.
14955   _.every = _.all = function(obj, predicate, context) {
14956     predicate = cb(predicate, context);
14957     var keys = !isArrayLike(obj) && _.keys(obj),
14958         length = (keys || obj).length;
14959     for (var index = 0; index < length; index++) {
14960       var currentKey = keys ? keys[index] : index;
14961       if (!predicate(obj[currentKey], currentKey, obj)) return false;
14962     }
14963     return true;
14964   };
14965
14966   // Determine if at least one element in the object matches a truth test.
14967   // Aliased as `any`.
14968   _.some = _.any = function(obj, predicate, context) {
14969     predicate = cb(predicate, context);
14970     var keys = !isArrayLike(obj) && _.keys(obj),
14971         length = (keys || obj).length;
14972     for (var index = 0; index < length; index++) {
14973       var currentKey = keys ? keys[index] : index;
14974       if (predicate(obj[currentKey], currentKey, obj)) return true;
14975     }
14976     return false;
14977   };
14978
14979   // Determine if the array or object contains a given item (using `===`).
14980   // Aliased as `includes` and `include`.
14981   _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
14982     if (!isArrayLike(obj)) obj = _.values(obj);
14983     if (typeof fromIndex != 'number' || guard) fromIndex = 0;
14984     return _.indexOf(obj, item, fromIndex) >= 0;
14985   };
14986
14987   // Invoke a method (with arguments) on every item in a collection.
14988   _.invoke = function(obj, method) {
14989     var args = slice.call(arguments, 2);
14990     var isFunc = _.isFunction(method);
14991     return _.map(obj, function(value) {
14992       var func = isFunc ? method : value[method];
14993       return func == null ? func : func.apply(value, args);
14994     });
14995   };
14996
14997   // Convenience version of a common use case of `map`: fetching a property.
14998   _.pluck = function(obj, key) {
14999     return _.map(obj, _.property(key));
15000   };
15001
15002   // Convenience version of a common use case of `filter`: selecting only objects
15003   // containing specific `key:value` pairs.
15004   _.where = function(obj, attrs) {
15005     return _.filter(obj, _.matcher(attrs));
15006   };
15007
15008   // Convenience version of a common use case of `find`: getting the first object
15009   // containing specific `key:value` pairs.
15010   _.findWhere = function(obj, attrs) {
15011     return _.find(obj, _.matcher(attrs));
15012   };
15013
15014   // Return the maximum element (or element-based computation).
15015   _.max = function(obj, iteratee, context) {
15016     var result = -Infinity, lastComputed = -Infinity,
15017         value, computed;
15018     if (iteratee == null && obj != null) {
15019       obj = isArrayLike(obj) ? obj : _.values(obj);
15020       for (var i = 0, length = obj.length; i < length; i++) {
15021         value = obj[i];
15022         if (value > result) {
15023           result = value;
15024         }
15025       }
15026     } else {
15027       iteratee = cb(iteratee, context);
15028       _.each(obj, function(value, index, list) {
15029         computed = iteratee(value, index, list);
15030         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
15031           result = value;
15032           lastComputed = computed;
15033         }
15034       });
15035     }
15036     return result;
15037   };
15038
15039   // Return the minimum element (or element-based computation).
15040   _.min = function(obj, iteratee, context) {
15041     var result = Infinity, lastComputed = Infinity,
15042         value, computed;
15043     if (iteratee == null && obj != null) {
15044       obj = isArrayLike(obj) ? obj : _.values(obj);
15045       for (var i = 0, length = obj.length; i < length; i++) {
15046         value = obj[i];
15047         if (value < result) {
15048           result = value;
15049         }
15050       }
15051     } else {
15052       iteratee = cb(iteratee, context);
15053       _.each(obj, function(value, index, list) {
15054         computed = iteratee(value, index, list);
15055         if (computed < lastComputed || computed === Infinity && result === Infinity) {
15056           result = value;
15057           lastComputed = computed;
15058         }
15059       });
15060     }
15061     return result;
15062   };
15063
15064   // Shuffle a collection, using the modern version of the
15065   // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
15066   _.shuffle = function(obj) {
15067     var set = isArrayLike(obj) ? obj : _.values(obj);
15068     var length = set.length;
15069     var shuffled = Array(length);
15070     for (var index = 0, rand; index < length; index++) {
15071       rand = _.random(0, index);
15072       if (rand !== index) shuffled[index] = shuffled[rand];
15073       shuffled[rand] = set[index];
15074     }
15075     return shuffled;
15076   };
15077
15078   // Sample **n** random values from a collection.
15079   // If **n** is not specified, returns a single random element.
15080   // The internal `guard` argument allows it to work with `map`.
15081   _.sample = function(obj, n, guard) {
15082     if (n == null || guard) {
15083       if (!isArrayLike(obj)) obj = _.values(obj);
15084       return obj[_.random(obj.length - 1)];
15085     }
15086     return _.shuffle(obj).slice(0, Math.max(0, n));
15087   };
15088
15089   // Sort the object's values by a criterion produced by an iteratee.
15090   _.sortBy = function(obj, iteratee, context) {
15091     iteratee = cb(iteratee, context);
15092     return _.pluck(_.map(obj, function(value, index, list) {
15093       return {
15094         value: value,
15095         index: index,
15096         criteria: iteratee(value, index, list)
15097       };
15098     }).sort(function(left, right) {
15099       var a = left.criteria;
15100       var b = right.criteria;
15101       if (a !== b) {
15102         if (a > b || a === void 0) return 1;
15103         if (a < b || b === void 0) return -1;
15104       }
15105       return left.index - right.index;
15106     }), 'value');
15107   };
15108
15109   // An internal function used for aggregate "group by" operations.
15110   var group = function(behavior) {
15111     return function(obj, iteratee, context) {
15112       var result = {};
15113       iteratee = cb(iteratee, context);
15114       _.each(obj, function(value, index) {
15115         var key = iteratee(value, index, obj);
15116         behavior(result, value, key);
15117       });
15118       return result;
15119     };
15120   };
15121
15122   // Groups the object's values by a criterion. Pass either a string attribute
15123   // to group by, or a function that returns the criterion.
15124   _.groupBy = group(function(result, value, key) {
15125     if (_.has(result, key)) result[key].push(value); else result[key] = [value];
15126   });
15127
15128   // Indexes the object's values by a criterion, similar to `groupBy`, but for
15129   // when you know that your index values will be unique.
15130   _.indexBy = group(function(result, value, key) {
15131     result[key] = value;
15132   });
15133
15134   // Counts instances of an object that group by a certain criterion. Pass
15135   // either a string attribute to count by, or a function that returns the
15136   // criterion.
15137   _.countBy = group(function(result, value, key) {
15138     if (_.has(result, key)) result[key]++; else result[key] = 1;
15139   });
15140
15141   // Safely create a real, live array from anything iterable.
15142   _.toArray = function(obj) {
15143     if (!obj) return [];
15144     if (_.isArray(obj)) return slice.call(obj);
15145     if (isArrayLike(obj)) return _.map(obj, _.identity);
15146     return _.values(obj);
15147   };
15148
15149   // Return the number of elements in an object.
15150   _.size = function(obj) {
15151     if (obj == null) return 0;
15152     return isArrayLike(obj) ? obj.length : _.keys(obj).length;
15153   };
15154
15155   // Split a collection into two arrays: one whose elements all satisfy the given
15156   // predicate, and one whose elements all do not satisfy the predicate.
15157   _.partition = function(obj, predicate, context) {
15158     predicate = cb(predicate, context);
15159     var pass = [], fail = [];
15160     _.each(obj, function(value, key, obj) {
15161       (predicate(value, key, obj) ? pass : fail).push(value);
15162     });
15163     return [pass, fail];
15164   };
15165
15166   // Array Functions
15167   // ---------------
15168
15169   // Get the first element of an array. Passing **n** will return the first N
15170   // values in the array. Aliased as `head` and `take`. The **guard** check
15171   // allows it to work with `_.map`.
15172   _.first = _.head = _.take = function(array, n, guard) {
15173     if (array == null) return void 0;
15174     if (n == null || guard) return array[0];
15175     return _.initial(array, array.length - n);
15176   };
15177
15178   // Returns everything but the last entry of the array. Especially useful on
15179   // the arguments object. Passing **n** will return all the values in
15180   // the array, excluding the last N.
15181   _.initial = function(array, n, guard) {
15182     return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
15183   };
15184
15185   // Get the last element of an array. Passing **n** will return the last N
15186   // values in the array.
15187   _.last = function(array, n, guard) {
15188     if (array == null) return void 0;
15189     if (n == null || guard) return array[array.length - 1];
15190     return _.rest(array, Math.max(0, array.length - n));
15191   };
15192
15193   // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
15194   // Especially useful on the arguments object. Passing an **n** will return
15195   // the rest N values in the array.
15196   _.rest = _.tail = _.drop = function(array, n, guard) {
15197     return slice.call(array, n == null || guard ? 1 : n);
15198   };
15199
15200   // Trim out all falsy values from an array.
15201   _.compact = function(array) {
15202     return _.filter(array, _.identity);
15203   };
15204
15205   // Internal implementation of a recursive `flatten` function.
15206   var flatten = function(input, shallow, strict, startIndex) {
15207     var output = [], idx = 0;
15208     for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
15209       var value = input[i];
15210       if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
15211         //flatten current level of array or arguments object
15212         if (!shallow) value = flatten(value, shallow, strict);
15213         var j = 0, len = value.length;
15214         output.length += len;
15215         while (j < len) {
15216           output[idx++] = value[j++];
15217         }
15218       } else if (!strict) {
15219         output[idx++] = value;
15220       }
15221     }
15222     return output;
15223   };
15224
15225   // Flatten out an array, either recursively (by default), or just one level.
15226   _.flatten = function(array, shallow) {
15227     return flatten(array, shallow, false);
15228   };
15229
15230   // Return a version of the array that does not contain the specified value(s).
15231   _.without = function(array) {
15232     return _.difference(array, slice.call(arguments, 1));
15233   };
15234
15235   // Produce a duplicate-free version of the array. If the array has already
15236   // been sorted, you have the option of using a faster algorithm.
15237   // Aliased as `unique`.
15238   _.uniq = _.unique = function(array, isSorted, iteratee, context) {
15239     if (!_.isBoolean(isSorted)) {
15240       context = iteratee;
15241       iteratee = isSorted;
15242       isSorted = false;
15243     }
15244     if (iteratee != null) iteratee = cb(iteratee, context);
15245     var result = [];
15246     var seen = [];
15247     for (var i = 0, length = getLength(array); i < length; i++) {
15248       var value = array[i],
15249           computed = iteratee ? iteratee(value, i, array) : value;
15250       if (isSorted) {
15251         if (!i || seen !== computed) result.push(value);
15252         seen = computed;
15253       } else if (iteratee) {
15254         if (!_.contains(seen, computed)) {
15255           seen.push(computed);
15256           result.push(value);
15257         }
15258       } else if (!_.contains(result, value)) {
15259         result.push(value);
15260       }
15261     }
15262     return result;
15263   };
15264
15265   // Produce an array that contains the union: each distinct element from all of
15266   // the passed-in arrays.
15267   _.union = function() {
15268     return _.uniq(flatten(arguments, true, true));
15269   };
15270
15271   // Produce an array that contains every item shared between all the
15272   // passed-in arrays.
15273   _.intersection = function(array) {
15274     var result = [];
15275     var argsLength = arguments.length;
15276     for (var i = 0, length = getLength(array); i < length; i++) {
15277       var item = array[i];
15278       if (_.contains(result, item)) continue;
15279       for (var j = 1; j < argsLength; j++) {
15280         if (!_.contains(arguments[j], item)) break;
15281       }
15282       if (j === argsLength) result.push(item);
15283     }
15284     return result;
15285   };
15286
15287   // Take the difference between one array and a number of other arrays.
15288   // Only the elements present in just the first array will remain.
15289   _.difference = function(array) {
15290     var rest = flatten(arguments, true, true, 1);
15291     return _.filter(array, function(value){
15292       return !_.contains(rest, value);
15293     });
15294   };
15295
15296   // Zip together multiple lists into a single array -- elements that share
15297   // an index go together.
15298   _.zip = function() {
15299     return _.unzip(arguments);
15300   };
15301
15302   // Complement of _.zip. Unzip accepts an array of arrays and groups
15303   // each array's elements on shared indices
15304   _.unzip = function(array) {
15305     var length = array && _.max(array, getLength).length || 0;
15306     var result = Array(length);
15307
15308     for (var index = 0; index < length; index++) {
15309       result[index] = _.pluck(array, index);
15310     }
15311     return result;
15312   };
15313
15314   // Converts lists into objects. Pass either a single array of `[key, value]`
15315   // pairs, or two parallel arrays of the same length -- one of keys, and one of
15316   // the corresponding values.
15317   _.object = function(list, values) {
15318     var result = {};
15319     for (var i = 0, length = getLength(list); i < length; i++) {
15320       if (values) {
15321         result[list[i]] = values[i];
15322       } else {
15323         result[list[i][0]] = list[i][1];
15324       }
15325     }
15326     return result;
15327   };
15328
15329   // Generator function to create the findIndex and findLastIndex functions
15330   function createPredicateIndexFinder(dir) {
15331     return function(array, predicate, context) {
15332       predicate = cb(predicate, context);
15333       var length = getLength(array);
15334       var index = dir > 0 ? 0 : length - 1;
15335       for (; index >= 0 && index < length; index += dir) {
15336         if (predicate(array[index], index, array)) return index;
15337       }
15338       return -1;
15339     };
15340   }
15341
15342   // Returns the first index on an array-like that passes a predicate test
15343   _.findIndex = createPredicateIndexFinder(1);
15344   _.findLastIndex = createPredicateIndexFinder(-1);
15345
15346   // Use a comparator function to figure out the smallest index at which
15347   // an object should be inserted so as to maintain order. Uses binary search.
15348   _.sortedIndex = function(array, obj, iteratee, context) {
15349     iteratee = cb(iteratee, context, 1);
15350     var value = iteratee(obj);
15351     var low = 0, high = getLength(array);
15352     while (low < high) {
15353       var mid = Math.floor((low + high) / 2);
15354       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
15355     }
15356     return low;
15357   };
15358
15359   // Generator function to create the indexOf and lastIndexOf functions
15360   function createIndexFinder(dir, predicateFind, sortedIndex) {
15361     return function(array, item, idx) {
15362       var i = 0, length = getLength(array);
15363       if (typeof idx == 'number') {
15364         if (dir > 0) {
15365             i = idx >= 0 ? idx : Math.max(idx + length, i);
15366         } else {
15367             length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
15368         }
15369       } else if (sortedIndex && idx && length) {
15370         idx = sortedIndex(array, item);
15371         return array[idx] === item ? idx : -1;
15372       }
15373       if (item !== item) {
15374         idx = predicateFind(slice.call(array, i, length), _.isNaN);
15375         return idx >= 0 ? idx + i : -1;
15376       }
15377       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
15378         if (array[idx] === item) return idx;
15379       }
15380       return -1;
15381     };
15382   }
15383
15384   // Return the position of the first occurrence of an item in an array,
15385   // or -1 if the item is not included in the array.
15386   // If the array is large and already in sort order, pass `true`
15387   // for **isSorted** to use binary search.
15388   _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
15389   _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
15390
15391   // Generate an integer Array containing an arithmetic progression. A port of
15392   // the native Python `range()` function. See
15393   // [the Python documentation](http://docs.python.org/library/functions.html#range).
15394   _.range = function(start, stop, step) {
15395     if (stop == null) {
15396       stop = start || 0;
15397       start = 0;
15398     }
15399     step = step || 1;
15400
15401     var length = Math.max(Math.ceil((stop - start) / step), 0);
15402     var range = Array(length);
15403
15404     for (var idx = 0; idx < length; idx++, start += step) {
15405       range[idx] = start;
15406     }
15407
15408     return range;
15409   };
15410
15411   // Function (ahem) Functions
15412   // ------------------
15413
15414   // Determines whether to execute a function as a constructor
15415   // or a normal function with the provided arguments
15416   var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
15417     if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
15418     var self = baseCreate(sourceFunc.prototype);
15419     var result = sourceFunc.apply(self, args);
15420     if (_.isObject(result)) return result;
15421     return self;
15422   };
15423
15424   // Create a function bound to a given object (assigning `this`, and arguments,
15425   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
15426   // available.
15427   _.bind = function(func, context) {
15428     if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
15429     if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
15430     var args = slice.call(arguments, 2);
15431     var bound = function() {
15432       return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
15433     };
15434     return bound;
15435   };
15436
15437   // Partially apply a function by creating a version that has had some of its
15438   // arguments pre-filled, without changing its dynamic `this` context. _ acts
15439   // as a placeholder, allowing any combination of arguments to be pre-filled.
15440   _.partial = function(func) {
15441     var boundArgs = slice.call(arguments, 1);
15442     var bound = function() {
15443       var position = 0, length = boundArgs.length;
15444       var args = Array(length);
15445       for (var i = 0; i < length; i++) {
15446         args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
15447       }
15448       while (position < arguments.length) args.push(arguments[position++]);
15449       return executeBound(func, bound, this, this, args);
15450     };
15451     return bound;
15452   };
15453
15454   // Bind a number of an object's methods to that object. Remaining arguments
15455   // are the method names to be bound. Useful for ensuring that all callbacks
15456   // defined on an object belong to it.
15457   _.bindAll = function(obj) {
15458     var i, length = arguments.length, key;
15459     if (length <= 1) throw new Error('bindAll must be passed function names');
15460     for (i = 1; i < length; i++) {
15461       key = arguments[i];
15462       obj[key] = _.bind(obj[key], obj);
15463     }
15464     return obj;
15465   };
15466
15467   // Memoize an expensive function by storing its results.
15468   _.memoize = function(func, hasher) {
15469     var memoize = function(key) {
15470       var cache = memoize.cache;
15471       var address = '' + (hasher ? hasher.apply(this, arguments) : key);
15472       if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
15473       return cache[address];
15474     };
15475     memoize.cache = {};
15476     return memoize;
15477   };
15478
15479   // Delays a function for the given number of milliseconds, and then calls
15480   // it with the arguments supplied.
15481   _.delay = function(func, wait) {
15482     var args = slice.call(arguments, 2);
15483     return setTimeout(function(){
15484       return func.apply(null, args);
15485     }, wait);
15486   };
15487
15488   // Defers a function, scheduling it to run after the current call stack has
15489   // cleared.
15490   _.defer = _.partial(_.delay, _, 1);
15491
15492   // Returns a function, that, when invoked, will only be triggered at most once
15493   // during a given window of time. Normally, the throttled function will run
15494   // as much as it can, without ever going more than once per `wait` duration;
15495   // but if you'd like to disable the execution on the leading edge, pass
15496   // `{leading: false}`. To disable execution on the trailing edge, ditto.
15497   _.throttle = function(func, wait, options) {
15498     var context, args, result;
15499     var timeout = null;
15500     var previous = 0;
15501     if (!options) options = {};
15502     var later = function() {
15503       previous = options.leading === false ? 0 : _.now();
15504       timeout = null;
15505       result = func.apply(context, args);
15506       if (!timeout) context = args = null;
15507     };
15508     return function() {
15509       var now = _.now();
15510       if (!previous && options.leading === false) previous = now;
15511       var remaining = wait - (now - previous);
15512       context = this;
15513       args = arguments;
15514       if (remaining <= 0 || remaining > wait) {
15515         if (timeout) {
15516           clearTimeout(timeout);
15517           timeout = null;
15518         }
15519         previous = now;
15520         result = func.apply(context, args);
15521         if (!timeout) context = args = null;
15522       } else if (!timeout && options.trailing !== false) {
15523         timeout = setTimeout(later, remaining);
15524       }
15525       return result;
15526     };
15527   };
15528
15529   // Returns a function, that, as long as it continues to be invoked, will not
15530   // be triggered. The function will be called after it stops being called for
15531   // N milliseconds. If `immediate` is passed, trigger the function on the
15532   // leading edge, instead of the trailing.
15533   _.debounce = function(func, wait, immediate) {
15534     var timeout, args, context, timestamp, result;
15535
15536     var later = function() {
15537       var last = _.now() - timestamp;
15538
15539       if (last < wait && last >= 0) {
15540         timeout = setTimeout(later, wait - last);
15541       } else {
15542         timeout = null;
15543         if (!immediate) {
15544           result = func.apply(context, args);
15545           if (!timeout) context = args = null;
15546         }
15547       }
15548     };
15549
15550     return function() {
15551       context = this;
15552       args = arguments;
15553       timestamp = _.now();
15554       var callNow = immediate && !timeout;
15555       if (!timeout) timeout = setTimeout(later, wait);
15556       if (callNow) {
15557         result = func.apply(context, args);
15558         context = args = null;
15559       }
15560
15561       return result;
15562     };
15563   };
15564
15565   // Returns the first function passed as an argument to the second,
15566   // allowing you to adjust arguments, run code before and after, and
15567   // conditionally execute the original function.
15568   _.wrap = function(func, wrapper) {
15569     return _.partial(wrapper, func);
15570   };
15571
15572   // Returns a negated version of the passed-in predicate.
15573   _.negate = function(predicate) {
15574     return function() {
15575       return !predicate.apply(this, arguments);
15576     };
15577   };
15578
15579   // Returns a function that is the composition of a list of functions, each
15580   // consuming the return value of the function that follows.
15581   _.compose = function() {
15582     var args = arguments;
15583     var start = args.length - 1;
15584     return function() {
15585       var i = start;
15586       var result = args[start].apply(this, arguments);
15587       while (i--) result = args[i].call(this, result);
15588       return result;
15589     };
15590   };
15591
15592   // Returns a function that will only be executed on and after the Nth call.
15593   _.after = function(times, func) {
15594     return function() {
15595       if (--times < 1) {
15596         return func.apply(this, arguments);
15597       }
15598     };
15599   };
15600
15601   // Returns a function that will only be executed up to (but not including) the Nth call.
15602   _.before = function(times, func) {
15603     var memo;
15604     return function() {
15605       if (--times > 0) {
15606         memo = func.apply(this, arguments);
15607       }
15608       if (times <= 1) func = null;
15609       return memo;
15610     };
15611   };
15612
15613   // Returns a function that will be executed at most one time, no matter how
15614   // often you call it. Useful for lazy initialization.
15615   _.once = _.partial(_.before, 2);
15616
15617   // Object Functions
15618   // ----------------
15619
15620   // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
15621   var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
15622   var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
15623                       'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
15624
15625   function collectNonEnumProps(obj, keys) {
15626     var nonEnumIdx = nonEnumerableProps.length;
15627     var constructor = obj.constructor;
15628     var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
15629
15630     // Constructor is a special case.
15631     var prop = 'constructor';
15632     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
15633
15634     while (nonEnumIdx--) {
15635       prop = nonEnumerableProps[nonEnumIdx];
15636       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
15637         keys.push(prop);
15638       }
15639     }
15640   }
15641
15642   // Retrieve the names of an object's own properties.
15643   // Delegates to **ECMAScript 5**'s native `Object.keys`
15644   _.keys = function(obj) {
15645     if (!_.isObject(obj)) return [];
15646     if (nativeKeys) return nativeKeys(obj);
15647     var keys = [];
15648     for (var key in obj) if (_.has(obj, key)) keys.push(key);
15649     // Ahem, IE < 9.
15650     if (hasEnumBug) collectNonEnumProps(obj, keys);
15651     return keys;
15652   };
15653
15654   // Retrieve all the property names of an object.
15655   _.allKeys = function(obj) {
15656     if (!_.isObject(obj)) return [];
15657     var keys = [];
15658     for (var key in obj) keys.push(key);
15659     // Ahem, IE < 9.
15660     if (hasEnumBug) collectNonEnumProps(obj, keys);
15661     return keys;
15662   };
15663
15664   // Retrieve the values of an object's properties.
15665   _.values = function(obj) {
15666     var keys = _.keys(obj);
15667     var length = keys.length;
15668     var values = Array(length);
15669     for (var i = 0; i < length; i++) {
15670       values[i] = obj[keys[i]];
15671     }
15672     return values;
15673   };
15674
15675   // Returns the results of applying the iteratee to each element of the object
15676   // In contrast to _.map it returns an object
15677   _.mapObject = function(obj, iteratee, context) {
15678     iteratee = cb(iteratee, context);
15679     var keys =  _.keys(obj),
15680           length = keys.length,
15681           results = {},
15682           currentKey;
15683       for (var index = 0; index < length; index++) {
15684         currentKey = keys[index];
15685         results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
15686       }
15687       return results;
15688   };
15689
15690   // Convert an object into a list of `[key, value]` pairs.
15691   _.pairs = function(obj) {
15692     var keys = _.keys(obj);
15693     var length = keys.length;
15694     var pairs = Array(length);
15695     for (var i = 0; i < length; i++) {
15696       pairs[i] = [keys[i], obj[keys[i]]];
15697     }
15698     return pairs;
15699   };
15700
15701   // Invert the keys and values of an object. The values must be serializable.
15702   _.invert = function(obj) {
15703     var result = {};
15704     var keys = _.keys(obj);
15705     for (var i = 0, length = keys.length; i < length; i++) {
15706       result[obj[keys[i]]] = keys[i];
15707     }
15708     return result;
15709   };
15710
15711   // Return a sorted list of the function names available on the object.
15712   // Aliased as `methods`
15713   _.functions = _.methods = function(obj) {
15714     var names = [];
15715     for (var key in obj) {
15716       if (_.isFunction(obj[key])) names.push(key);
15717     }
15718     return names.sort();
15719   };
15720
15721   // Extend a given object with all the properties in passed-in object(s).
15722   _.extend = createAssigner(_.allKeys);
15723
15724   // Assigns a given object with all the own properties in the passed-in object(s)
15725   // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
15726   _.extendOwn = _.assign = createAssigner(_.keys);
15727
15728   // Returns the first key on an object that passes a predicate test
15729   _.findKey = function(obj, predicate, context) {
15730     predicate = cb(predicate, context);
15731     var keys = _.keys(obj), key;
15732     for (var i = 0, length = keys.length; i < length; i++) {
15733       key = keys[i];
15734       if (predicate(obj[key], key, obj)) return key;
15735     }
15736   };
15737
15738   // Return a copy of the object only containing the whitelisted properties.
15739   _.pick = function(object, oiteratee, context) {
15740     var result = {}, obj = object, iteratee, keys;
15741     if (obj == null) return result;
15742     if (_.isFunction(oiteratee)) {
15743       keys = _.allKeys(obj);
15744       iteratee = optimizeCb(oiteratee, context);
15745     } else {
15746       keys = flatten(arguments, false, false, 1);
15747       iteratee = function(value, key, obj) { return key in obj; };
15748       obj = Object(obj);
15749     }
15750     for (var i = 0, length = keys.length; i < length; i++) {
15751       var key = keys[i];
15752       var value = obj[key];
15753       if (iteratee(value, key, obj)) result[key] = value;
15754     }
15755     return result;
15756   };
15757
15758    // Return a copy of the object without the blacklisted properties.
15759   _.omit = function(obj, iteratee, context) {
15760     if (_.isFunction(iteratee)) {
15761       iteratee = _.negate(iteratee);
15762     } else {
15763       var keys = _.map(flatten(arguments, false, false, 1), String);
15764       iteratee = function(value, key) {
15765         return !_.contains(keys, key);
15766       };
15767     }
15768     return _.pick(obj, iteratee, context);
15769   };
15770
15771   // Fill in a given object with default properties.
15772   _.defaults = createAssigner(_.allKeys, true);
15773
15774   // Creates an object that inherits from the given prototype object.
15775   // If additional properties are provided then they will be added to the
15776   // created object.
15777   _.create = function(prototype, props) {
15778     var result = baseCreate(prototype);
15779     if (props) _.extendOwn(result, props);
15780     return result;
15781   };
15782
15783   // Create a (shallow-cloned) duplicate of an object.
15784   _.clone = function(obj) {
15785     if (!_.isObject(obj)) return obj;
15786     return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
15787   };
15788
15789   // Invokes interceptor with the obj, and then returns obj.
15790   // The primary purpose of this method is to "tap into" a method chain, in
15791   // order to perform operations on intermediate results within the chain.
15792   _.tap = function(obj, interceptor) {
15793     interceptor(obj);
15794     return obj;
15795   };
15796
15797   // Returns whether an object has a given set of `key:value` pairs.
15798   _.isMatch = function(object, attrs) {
15799     var keys = _.keys(attrs), length = keys.length;
15800     if (object == null) return !length;
15801     var obj = Object(object);
15802     for (var i = 0; i < length; i++) {
15803       var key = keys[i];
15804       if (attrs[key] !== obj[key] || !(key in obj)) return false;
15805     }
15806     return true;
15807   };
15808
15809
15810   // Internal recursive comparison function for `isEqual`.
15811   var eq = function(a, b, aStack, bStack) {
15812     // Identical objects are equal. `0 === -0`, but they aren't identical.
15813     // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
15814     if (a === b) return a !== 0 || 1 / a === 1 / b;
15815     // A strict comparison is necessary because `null == undefined`.
15816     if (a == null || b == null) return a === b;
15817     // Unwrap any wrapped objects.
15818     if (a instanceof _) a = a._wrapped;
15819     if (b instanceof _) b = b._wrapped;
15820     // Compare `[[Class]]` names.
15821     var className = toString.call(a);
15822     if (className !== toString.call(b)) return false;
15823     switch (className) {
15824       // Strings, numbers, regular expressions, dates, and booleans are compared by value.
15825       case '[object RegExp]':
15826       // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
15827       case '[object String]':
15828         // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
15829         // equivalent to `new String("5")`.
15830         return '' + a === '' + b;
15831       case '[object Number]':
15832         // `NaN`s are equivalent, but non-reflexive.
15833         // Object(NaN) is equivalent to NaN
15834         if (+a !== +a) return +b !== +b;
15835         // An `egal` comparison is performed for other numeric values.
15836         return +a === 0 ? 1 / +a === 1 / b : +a === +b;
15837       case '[object Date]':
15838       case '[object Boolean]':
15839         // Coerce dates and booleans to numeric primitive values. Dates are compared by their
15840         // millisecond representations. Note that invalid dates with millisecond representations
15841         // of `NaN` are not equivalent.
15842         return +a === +b;
15843     }
15844
15845     var areArrays = className === '[object Array]';
15846     if (!areArrays) {
15847       if (typeof a != 'object' || typeof b != 'object') return false;
15848
15849       // Objects with different constructors are not equivalent, but `Object`s or `Array`s
15850       // from different frames are.
15851       var aCtor = a.constructor, bCtor = b.constructor;
15852       if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
15853                                _.isFunction(bCtor) && bCtor instanceof bCtor)
15854                           && ('constructor' in a && 'constructor' in b)) {
15855         return false;
15856       }
15857     }
15858     // Assume equality for cyclic structures. The algorithm for detecting cyclic
15859     // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
15860
15861     // Initializing stack of traversed objects.
15862     // It's done here since we only need them for objects and arrays comparison.
15863     aStack = aStack || [];
15864     bStack = bStack || [];
15865     var length = aStack.length;
15866     while (length--) {
15867       // Linear search. Performance is inversely proportional to the number of
15868       // unique nested structures.
15869       if (aStack[length] === a) return bStack[length] === b;
15870     }
15871
15872     // Add the first object to the stack of traversed objects.
15873     aStack.push(a);
15874     bStack.push(b);
15875
15876     // Recursively compare objects and arrays.
15877     if (areArrays) {
15878       // Compare array lengths to determine if a deep comparison is necessary.
15879       length = a.length;
15880       if (length !== b.length) return false;
15881       // Deep compare the contents, ignoring non-numeric properties.
15882       while (length--) {
15883         if (!eq(a[length], b[length], aStack, bStack)) return false;
15884       }
15885     } else {
15886       // Deep compare objects.
15887       var keys = _.keys(a), key;
15888       length = keys.length;
15889       // Ensure that both objects contain the same number of properties before comparing deep equality.
15890       if (_.keys(b).length !== length) return false;
15891       while (length--) {
15892         // Deep compare each member
15893         key = keys[length];
15894         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
15895       }
15896     }
15897     // Remove the first object from the stack of traversed objects.
15898     aStack.pop();
15899     bStack.pop();
15900     return true;
15901   };
15902
15903   // Perform a deep comparison to check if two objects are equal.
15904   _.isEqual = function(a, b) {
15905     return eq(a, b);
15906   };
15907
15908   // Is a given array, string, or object empty?
15909   // An "empty" object has no enumerable own-properties.
15910   _.isEmpty = function(obj) {
15911     if (obj == null) return true;
15912     if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
15913     return _.keys(obj).length === 0;
15914   };
15915
15916   // Is a given value a DOM element?
15917   _.isElement = function(obj) {
15918     return !!(obj && obj.nodeType === 1);
15919   };
15920
15921   // Is a given value an array?
15922   // Delegates to ECMA5's native Array.isArray
15923   _.isArray = nativeIsArray || function(obj) {
15924     return toString.call(obj) === '[object Array]';
15925   };
15926
15927   // Is a given variable an object?
15928   _.isObject = function(obj) {
15929     var type = typeof obj;
15930     return type === 'function' || type === 'object' && !!obj;
15931   };
15932
15933   // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
15934   _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
15935     _['is' + name] = function(obj) {
15936       return toString.call(obj) === '[object ' + name + ']';
15937     };
15938   });
15939
15940   // Define a fallback version of the method in browsers (ahem, IE < 9), where
15941   // there isn't any inspectable "Arguments" type.
15942   if (!_.isArguments(arguments)) {
15943     _.isArguments = function(obj) {
15944       return _.has(obj, 'callee');
15945     };
15946   }
15947
15948   // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
15949   // IE 11 (#1621), and in Safari 8 (#1929).
15950   if (typeof /./ != 'function' && typeof Int8Array != 'object') {
15951     _.isFunction = function(obj) {
15952       return typeof obj == 'function' || false;
15953     };
15954   }
15955
15956   // Is a given object a finite number?
15957   _.isFinite = function(obj) {
15958     return isFinite(obj) && !isNaN(parseFloat(obj));
15959   };
15960
15961   // Is the given value `NaN`? (NaN is the only number which does not equal itself).
15962   _.isNaN = function(obj) {
15963     return _.isNumber(obj) && obj !== +obj;
15964   };
15965
15966   // Is a given value a boolean?
15967   _.isBoolean = function(obj) {
15968     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
15969   };
15970
15971   // Is a given value equal to null?
15972   _.isNull = function(obj) {
15973     return obj === null;
15974   };
15975
15976   // Is a given variable undefined?
15977   _.isUndefined = function(obj) {
15978     return obj === void 0;
15979   };
15980
15981   // Shortcut function for checking if an object has a given property directly
15982   // on itself (in other words, not on a prototype).
15983   _.has = function(obj, key) {
15984     return obj != null && hasOwnProperty.call(obj, key);
15985   };
15986
15987   // Utility Functions
15988   // -----------------
15989
15990   // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
15991   // previous owner. Returns a reference to the Underscore object.
15992   _.noConflict = function() {
15993     root._ = previousUnderscore;
15994     return this;
15995   };
15996
15997   // Keep the identity function around for default iteratees.
15998   _.identity = function(value) {
15999     return value;
16000   };
16001
16002   // Predicate-generating functions. Often useful outside of Underscore.
16003   _.constant = function(value) {
16004     return function() {
16005       return value;
16006     };
16007   };
16008
16009   _.noop = function(){};
16010
16011   _.property = property;
16012
16013   // Generates a function for a given object that returns a given property.
16014   _.propertyOf = function(obj) {
16015     return obj == null ? function(){} : function(key) {
16016       return obj[key];
16017     };
16018   };
16019
16020   // Returns a predicate for checking whether an object has a given set of
16021   // `key:value` pairs.
16022   _.matcher = _.matches = function(attrs) {
16023     attrs = _.extendOwn({}, attrs);
16024     return function(obj) {
16025       return _.isMatch(obj, attrs);
16026     };
16027   };
16028
16029   // Run a function **n** times.
16030   _.times = function(n, iteratee, context) {
16031     var accum = Array(Math.max(0, n));
16032     iteratee = optimizeCb(iteratee, context, 1);
16033     for (var i = 0; i < n; i++) accum[i] = iteratee(i);
16034     return accum;
16035   };
16036
16037   // Return a random integer between min and max (inclusive).
16038   _.random = function(min, max) {
16039     if (max == null) {
16040       max = min;
16041       min = 0;
16042     }
16043     return min + Math.floor(Math.random() * (max - min + 1));
16044   };
16045
16046   // A (possibly faster) way to get the current timestamp as an integer.
16047   _.now = Date.now || function() {
16048     return new Date().getTime();
16049   };
16050
16051    // List of HTML entities for escaping.
16052   var escapeMap = {
16053     '&': '&amp;',
16054     '<': '&lt;',
16055     '>': '&gt;',
16056     '"': '&quot;',
16057     "'": '&#x27;',
16058     '`': '&#x60;'
16059   };
16060   var unescapeMap = _.invert(escapeMap);
16061
16062   // Functions for escaping and unescaping strings to/from HTML interpolation.
16063   var createEscaper = function(map) {
16064     var escaper = function(match) {
16065       return map[match];
16066     };
16067     // Regexes for identifying a key that needs to be escaped
16068     var source = '(?:' + _.keys(map).join('|') + ')';
16069     var testRegexp = RegExp(source);
16070     var replaceRegexp = RegExp(source, 'g');
16071     return function(string) {
16072       string = string == null ? '' : '' + string;
16073       return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
16074     };
16075   };
16076   _.escape = createEscaper(escapeMap);
16077   _.unescape = createEscaper(unescapeMap);
16078
16079   // If the value of the named `property` is a function then invoke it with the
16080   // `object` as context; otherwise, return it.
16081   _.result = function(object, property, fallback) {
16082     var value = object == null ? void 0 : object[property];
16083     if (value === void 0) {
16084       value = fallback;
16085     }
16086     return _.isFunction(value) ? value.call(object) : value;
16087   };
16088
16089   // Generate a unique integer id (unique within the entire client session).
16090   // Useful for temporary DOM ids.
16091   var idCounter = 0;
16092   _.uniqueId = function(prefix) {
16093     var id = ++idCounter + '';
16094     return prefix ? prefix + id : id;
16095   };
16096
16097   // By default, Underscore uses ERB-style template delimiters, change the
16098   // following template settings to use alternative delimiters.
16099   _.templateSettings = {
16100     evaluate    : /<%([\s\S]+?)%>/g,
16101     interpolate : /<%=([\s\S]+?)%>/g,
16102     escape      : /<%-([\s\S]+?)%>/g
16103   };
16104
16105   // When customizing `templateSettings`, if you don't want to define an
16106   // interpolation, evaluation or escaping regex, we need one that is
16107   // guaranteed not to match.
16108   var noMatch = /(.)^/;
16109
16110   // Certain characters need to be escaped so that they can be put into a
16111   // string literal.
16112   var escapes = {
16113     "'":      "'",
16114     '\\':     '\\',
16115     '\r':     'r',
16116     '\n':     'n',
16117     '\u2028': 'u2028',
16118     '\u2029': 'u2029'
16119   };
16120
16121   var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
16122
16123   var escapeChar = function(match) {
16124     return '\\' + escapes[match];
16125   };
16126
16127   // JavaScript micro-templating, similar to John Resig's implementation.
16128   // Underscore templating handles arbitrary delimiters, preserves whitespace,
16129   // and correctly escapes quotes within interpolated code.
16130   // NB: `oldSettings` only exists for backwards compatibility.
16131   _.template = function(text, settings, oldSettings) {
16132     if (!settings && oldSettings) settings = oldSettings;
16133     settings = _.defaults({}, settings, _.templateSettings);
16134
16135     // Combine delimiters into one regular expression via alternation.
16136     var matcher = RegExp([
16137       (settings.escape || noMatch).source,
16138       (settings.interpolate || noMatch).source,
16139       (settings.evaluate || noMatch).source
16140     ].join('|') + '|$', 'g');
16141
16142     // Compile the template source, escaping string literals appropriately.
16143     var index = 0;
16144     var source = "__p+='";
16145     text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
16146       source += text.slice(index, offset).replace(escaper, escapeChar);
16147       index = offset + match.length;
16148
16149       if (escape) {
16150         source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
16151       } else if (interpolate) {
16152         source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
16153       } else if (evaluate) {
16154         source += "';\n" + evaluate + "\n__p+='";
16155       }
16156
16157       // Adobe VMs need the match returned to produce the correct offest.
16158       return match;
16159     });
16160     source += "';\n";
16161
16162     // If a variable is not specified, place data values in local scope.
16163     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
16164
16165     source = "var __t,__p='',__j=Array.prototype.join," +
16166       "print=function(){__p+=__j.call(arguments,'');};\n" +
16167       source + 'return __p;\n';
16168
16169     try {
16170       var render = new Function(settings.variable || 'obj', '_', source);
16171     } catch (e) {
16172       e.source = source;
16173       throw e;
16174     }
16175
16176     var template = function(data) {
16177       return render.call(this, data, _);
16178     };
16179
16180     // Provide the compiled source as a convenience for precompilation.
16181     var argument = settings.variable || 'obj';
16182     template.source = 'function(' + argument + '){\n' + source + '}';
16183
16184     return template;
16185   };
16186
16187   // Add a "chain" function. Start chaining a wrapped Underscore object.
16188   _.chain = function(obj) {
16189     var instance = _(obj);
16190     instance._chain = true;
16191     return instance;
16192   };
16193
16194   // OOP
16195   // ---------------
16196   // If Underscore is called as a function, it returns a wrapped object that
16197   // can be used OO-style. This wrapper holds altered versions of all the
16198   // underscore functions. Wrapped objects may be chained.
16199
16200   // Helper function to continue chaining intermediate results.
16201   var result = function(instance, obj) {
16202     return instance._chain ? _(obj).chain() : obj;
16203   };
16204
16205   // Add your own custom functions to the Underscore object.
16206   _.mixin = function(obj) {
16207     _.each(_.functions(obj), function(name) {
16208       var func = _[name] = obj[name];
16209       _.prototype[name] = function() {
16210         var args = [this._wrapped];
16211         push.apply(args, arguments);
16212         return result(this, func.apply(_, args));
16213       };
16214     });
16215   };
16216
16217   // Add all of the Underscore functions to the wrapper object.
16218   _.mixin(_);
16219
16220   // Add all mutator Array functions to the wrapper.
16221   _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
16222     var method = ArrayProto[name];
16223     _.prototype[name] = function() {
16224       var obj = this._wrapped;
16225       method.apply(obj, arguments);
16226       if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
16227       return result(this, obj);
16228     };
16229   });
16230
16231   // Add all accessor Array functions to the wrapper.
16232   _.each(['concat', 'join', 'slice'], function(name) {
16233     var method = ArrayProto[name];
16234     _.prototype[name] = function() {
16235       return result(this, method.apply(this._wrapped, arguments));
16236     };
16237   });
16238
16239   // Extracts the result from a wrapped and chained object.
16240   _.prototype.value = function() {
16241     return this._wrapped;
16242   };
16243
16244   // Provide unwrapping proxy for some methods used in engine operations
16245   // such as arithmetic and JSON stringification.
16246   _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
16247
16248   _.prototype.toString = function() {
16249     return '' + this._wrapped;
16250   };
16251
16252   // AMD registration happens at the end for compatibility with AMD loaders
16253   // that may not enforce next-turn semantics on modules. Even though general
16254   // practice for AMD registration is to be anonymous, underscore registers
16255   // as a named module because, like jQuery, it is a base library that is
16256   // popular enough to be bundled in a third party lib, but not be part of
16257   // an AMD load request. Those cases could generate an error when an
16258   // anonymous define() is called outside of a loader request.
16259   if (typeof define === 'function' && define.amd) {
16260     define('underscore', [], function() {
16261       return _;
16262     });
16263   }
16264 }.call(this));
16265
16266 },{}],183:[function(require,module,exports){
16267 var createElement = require("./vdom/create-element.js")
16268
16269 module.exports = createElement
16270
16271 },{"./vdom/create-element.js":189}],184:[function(require,module,exports){
16272 var diff = require("./vtree/diff.js")
16273
16274 module.exports = diff
16275
16276 },{"./vtree/diff.js":209}],185:[function(require,module,exports){
16277 var h = require("./virtual-hyperscript/index.js")
16278
16279 module.exports = h
16280
16281 },{"./virtual-hyperscript/index.js":196}],186:[function(require,module,exports){
16282 var diff = require("./diff.js")
16283 var patch = require("./patch.js")
16284 var h = require("./h.js")
16285 var create = require("./create-element.js")
16286 var VNode = require('./vnode/vnode.js')
16287 var VText = require('./vnode/vtext.js')
16288
16289 module.exports = {
16290     diff: diff,
16291     patch: patch,
16292     h: h,
16293     create: create,
16294     VNode: VNode,
16295     VText: VText
16296 }
16297
16298 },{"./create-element.js":183,"./diff.js":184,"./h.js":185,"./patch.js":187,"./vnode/vnode.js":205,"./vnode/vtext.js":207}],187:[function(require,module,exports){
16299 var patch = require("./vdom/patch.js")
16300
16301 module.exports = patch
16302
16303 },{"./vdom/patch.js":192}],188:[function(require,module,exports){
16304 var isObject = require("is-object")
16305 var isHook = require("../vnode/is-vhook.js")
16306
16307 module.exports = applyProperties
16308
16309 function applyProperties(node, props, previous) {
16310     for (var propName in props) {
16311         var propValue = props[propName]
16312
16313         if (propValue === undefined) {
16314             removeProperty(node, propName, propValue, previous);
16315         } else if (isHook(propValue)) {
16316             removeProperty(node, propName, propValue, previous)
16317             if (propValue.hook) {
16318                 propValue.hook(node,
16319                     propName,
16320                     previous ? previous[propName] : undefined)
16321             }
16322         } else {
16323             if (isObject(propValue)) {
16324                 patchObject(node, props, previous, propName, propValue);
16325             } else {
16326                 node[propName] = propValue
16327             }
16328         }
16329     }
16330 }
16331
16332 function removeProperty(node, propName, propValue, previous) {
16333     if (previous) {
16334         var previousValue = previous[propName]
16335
16336         if (!isHook(previousValue)) {
16337             if (propName === "attributes") {
16338                 for (var attrName in previousValue) {
16339                     node.removeAttribute(attrName)
16340                 }
16341             } else if (propName === "style") {
16342                 for (var i in previousValue) {
16343                     node.style[i] = ""
16344                 }
16345             } else if (typeof previousValue === "string") {
16346                 node[propName] = ""
16347             } else {
16348                 node[propName] = null
16349             }
16350         } else if (previousValue.unhook) {
16351             previousValue.unhook(node, propName, propValue)
16352         }
16353     }
16354 }
16355
16356 function patchObject(node, props, previous, propName, propValue) {
16357     var previousValue = previous ? previous[propName] : undefined
16358
16359     // Set attributes
16360     if (propName === "attributes") {
16361         for (var attrName in propValue) {
16362             var attrValue = propValue[attrName]
16363
16364             if (attrValue === undefined) {
16365                 node.removeAttribute(attrName)
16366             } else {
16367                 node.setAttribute(attrName, attrValue)
16368             }
16369         }
16370
16371         return
16372     }
16373
16374     if(previousValue && isObject(previousValue) &&
16375         getPrototype(previousValue) !== getPrototype(propValue)) {
16376         node[propName] = propValue
16377         return
16378     }
16379
16380     if (!isObject(node[propName])) {
16381         node[propName] = {}
16382     }
16383
16384     var replacer = propName === "style" ? "" : undefined
16385
16386     for (var k in propValue) {
16387         var value = propValue[k]
16388         node[propName][k] = (value === undefined) ? replacer : value
16389     }
16390 }
16391
16392 function getPrototype(value) {
16393     if (Object.getPrototypeOf) {
16394         return Object.getPrototypeOf(value)
16395     } else if (value.__proto__) {
16396         return value.__proto__
16397     } else if (value.constructor) {
16398         return value.constructor.prototype
16399     }
16400 }
16401
16402 },{"../vnode/is-vhook.js":200,"is-object":20}],189:[function(require,module,exports){
16403 var document = require("global/document")
16404
16405 var applyProperties = require("./apply-properties")
16406
16407 var isVNode = require("../vnode/is-vnode.js")
16408 var isVText = require("../vnode/is-vtext.js")
16409 var isWidget = require("../vnode/is-widget.js")
16410 var handleThunk = require("../vnode/handle-thunk.js")
16411
16412 module.exports = createElement
16413
16414 function createElement(vnode, opts) {
16415     var doc = opts ? opts.document || document : document
16416     var warn = opts ? opts.warn : null
16417
16418     vnode = handleThunk(vnode).a
16419
16420     if (isWidget(vnode)) {
16421         return vnode.init()
16422     } else if (isVText(vnode)) {
16423         return doc.createTextNode(vnode.text)
16424     } else if (!isVNode(vnode)) {
16425         if (warn) {
16426             warn("Item is not a valid virtual dom node", vnode)
16427         }
16428         return null
16429     }
16430
16431     var node = (vnode.namespace === null) ?
16432         doc.createElement(vnode.tagName) :
16433         doc.createElementNS(vnode.namespace, vnode.tagName)
16434
16435     var props = vnode.properties
16436     applyProperties(node, props)
16437
16438     var children = vnode.children
16439
16440     for (var i = 0; i < children.length; i++) {
16441         var childNode = createElement(children[i], opts)
16442         if (childNode) {
16443             node.appendChild(childNode)
16444         }
16445     }
16446
16447     return node
16448 }
16449
16450 },{"../vnode/handle-thunk.js":198,"../vnode/is-vnode.js":201,"../vnode/is-vtext.js":202,"../vnode/is-widget.js":203,"./apply-properties":188,"global/document":16}],190:[function(require,module,exports){
16451 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
16452 // We don't want to read all of the DOM nodes in the tree so we use
16453 // the in-order tree indexing to eliminate recursion down certain branches.
16454 // We only recurse into a DOM node if we know that it contains a child of
16455 // interest.
16456
16457 var noChild = {}
16458
16459 module.exports = domIndex
16460
16461 function domIndex(rootNode, tree, indices, nodes) {
16462     if (!indices || indices.length === 0) {
16463         return {}
16464     } else {
16465         indices.sort(ascending)
16466         return recurse(rootNode, tree, indices, nodes, 0)
16467     }
16468 }
16469
16470 function recurse(rootNode, tree, indices, nodes, rootIndex) {
16471     nodes = nodes || {}
16472
16473
16474     if (rootNode) {
16475         if (indexInRange(indices, rootIndex, rootIndex)) {
16476             nodes[rootIndex] = rootNode
16477         }
16478
16479         var vChildren = tree.children
16480
16481         if (vChildren) {
16482
16483             var childNodes = rootNode.childNodes
16484
16485             for (var i = 0; i < tree.children.length; i++) {
16486                 rootIndex += 1
16487
16488                 var vChild = vChildren[i] || noChild
16489                 var nextIndex = rootIndex + (vChild.count || 0)
16490
16491                 // skip recursion down the tree if there are no nodes down here
16492                 if (indexInRange(indices, rootIndex, nextIndex)) {
16493                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
16494                 }
16495
16496                 rootIndex = nextIndex
16497             }
16498         }
16499     }
16500
16501     return nodes
16502 }
16503
16504 // Binary search for an index in the interval [left, right]
16505 function indexInRange(indices, left, right) {
16506     if (indices.length === 0) {
16507         return false
16508     }
16509
16510     var minIndex = 0
16511     var maxIndex = indices.length - 1
16512     var currentIndex
16513     var currentItem
16514
16515     while (minIndex <= maxIndex) {
16516         currentIndex = ((maxIndex + minIndex) / 2) >> 0
16517         currentItem = indices[currentIndex]
16518
16519         if (minIndex === maxIndex) {
16520             return currentItem >= left && currentItem <= right
16521         } else if (currentItem < left) {
16522             minIndex = currentIndex + 1
16523         } else  if (currentItem > right) {
16524             maxIndex = currentIndex - 1
16525         } else {
16526             return true
16527         }
16528     }
16529
16530     return false;
16531 }
16532
16533 function ascending(a, b) {
16534     return a > b ? 1 : -1
16535 }
16536
16537 },{}],191:[function(require,module,exports){
16538 var applyProperties = require("./apply-properties")
16539
16540 var isWidget = require("../vnode/is-widget.js")
16541 var VPatch = require("../vnode/vpatch.js")
16542
16543 var updateWidget = require("./update-widget")
16544
16545 module.exports = applyPatch
16546
16547 function applyPatch(vpatch, domNode, renderOptions) {
16548     var type = vpatch.type
16549     var vNode = vpatch.vNode
16550     var patch = vpatch.patch
16551
16552     switch (type) {
16553         case VPatch.REMOVE:
16554             return removeNode(domNode, vNode)
16555         case VPatch.INSERT:
16556             return insertNode(domNode, patch, renderOptions)
16557         case VPatch.VTEXT:
16558             return stringPatch(domNode, vNode, patch, renderOptions)
16559         case VPatch.WIDGET:
16560             return widgetPatch(domNode, vNode, patch, renderOptions)
16561         case VPatch.VNODE:
16562             return vNodePatch(domNode, vNode, patch, renderOptions)
16563         case VPatch.ORDER:
16564             reorderChildren(domNode, patch)
16565             return domNode
16566         case VPatch.PROPS:
16567             applyProperties(domNode, patch, vNode.properties)
16568             return domNode
16569         case VPatch.THUNK:
16570             return replaceRoot(domNode,
16571                 renderOptions.patch(domNode, patch, renderOptions))
16572         default:
16573             return domNode
16574     }
16575 }
16576
16577 function removeNode(domNode, vNode) {
16578     var parentNode = domNode.parentNode
16579
16580     if (parentNode) {
16581         parentNode.removeChild(domNode)
16582     }
16583
16584     destroyWidget(domNode, vNode);
16585
16586     return null
16587 }
16588
16589 function insertNode(parentNode, vNode, renderOptions) {
16590     var newNode = renderOptions.render(vNode, renderOptions)
16591
16592     if (parentNode) {
16593         parentNode.appendChild(newNode)
16594     }
16595
16596     return parentNode
16597 }
16598
16599 function stringPatch(domNode, leftVNode, vText, renderOptions) {
16600     var newNode
16601
16602     if (domNode.nodeType === 3) {
16603         domNode.replaceData(0, domNode.length, vText.text)
16604         newNode = domNode
16605     } else {
16606         var parentNode = domNode.parentNode
16607         newNode = renderOptions.render(vText, renderOptions)
16608
16609         if (parentNode && newNode !== domNode) {
16610             parentNode.replaceChild(newNode, domNode)
16611         }
16612     }
16613
16614     return newNode
16615 }
16616
16617 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
16618     var updating = updateWidget(leftVNode, widget)
16619     var newNode
16620
16621     if (updating) {
16622         newNode = widget.update(leftVNode, domNode) || domNode
16623     } else {
16624         newNode = renderOptions.render(widget, renderOptions)
16625     }
16626
16627     var parentNode = domNode.parentNode
16628
16629     if (parentNode && newNode !== domNode) {
16630         parentNode.replaceChild(newNode, domNode)
16631     }
16632
16633     if (!updating) {
16634         destroyWidget(domNode, leftVNode)
16635     }
16636
16637     return newNode
16638 }
16639
16640 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
16641     var parentNode = domNode.parentNode
16642     var newNode = renderOptions.render(vNode, renderOptions)
16643
16644     if (parentNode && newNode !== domNode) {
16645         parentNode.replaceChild(newNode, domNode)
16646     }
16647
16648     return newNode
16649 }
16650
16651 function destroyWidget(domNode, w) {
16652     if (typeof w.destroy === "function" && isWidget(w)) {
16653         w.destroy(domNode)
16654     }
16655 }
16656
16657 function reorderChildren(domNode, moves) {
16658     var childNodes = domNode.childNodes
16659     var keyMap = {}
16660     var node
16661     var remove
16662     var insert
16663
16664     for (var i = 0; i < moves.removes.length; i++) {
16665         remove = moves.removes[i]
16666         node = childNodes[remove.from]
16667         if (remove.key) {
16668             keyMap[remove.key] = node
16669         }
16670         domNode.removeChild(node)
16671     }
16672
16673     var length = childNodes.length
16674     for (var j = 0; j < moves.inserts.length; j++) {
16675         insert = moves.inserts[j]
16676         node = keyMap[insert.key]
16677         // this is the weirdest bug i've ever seen in webkit
16678         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
16679     }
16680 }
16681
16682 function replaceRoot(oldRoot, newRoot) {
16683     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
16684         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
16685     }
16686
16687     return newRoot;
16688 }
16689
16690 },{"../vnode/is-widget.js":203,"../vnode/vpatch.js":206,"./apply-properties":188,"./update-widget":193}],192:[function(require,module,exports){
16691 var document = require("global/document")
16692 var isArray = require("x-is-array")
16693
16694 var render = require("./create-element")
16695 var domIndex = require("./dom-index")
16696 var patchOp = require("./patch-op")
16697 module.exports = patch
16698
16699 function patch(rootNode, patches, renderOptions) {
16700     renderOptions = renderOptions || {}
16701     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
16702         ? renderOptions.patch
16703         : patchRecursive
16704     renderOptions.render = renderOptions.render || render
16705
16706     return renderOptions.patch(rootNode, patches, renderOptions)
16707 }
16708
16709 function patchRecursive(rootNode, patches, renderOptions) {
16710     var indices = patchIndices(patches)
16711
16712     if (indices.length === 0) {
16713         return rootNode
16714     }
16715
16716     var index = domIndex(rootNode, patches.a, indices)
16717     var ownerDocument = rootNode.ownerDocument
16718
16719     if (!renderOptions.document && ownerDocument !== document) {
16720         renderOptions.document = ownerDocument
16721     }
16722
16723     for (var i = 0; i < indices.length; i++) {
16724         var nodeIndex = indices[i]
16725         rootNode = applyPatch(rootNode,
16726             index[nodeIndex],
16727             patches[nodeIndex],
16728             renderOptions)
16729     }
16730
16731     return rootNode
16732 }
16733
16734 function applyPatch(rootNode, domNode, patchList, renderOptions) {
16735     if (!domNode) {
16736         return rootNode
16737     }
16738
16739     var newNode
16740
16741     if (isArray(patchList)) {
16742         for (var i = 0; i < patchList.length; i++) {
16743             newNode = patchOp(patchList[i], domNode, renderOptions)
16744
16745             if (domNode === rootNode) {
16746                 rootNode = newNode
16747             }
16748         }
16749     } else {
16750         newNode = patchOp(patchList, domNode, renderOptions)
16751
16752         if (domNode === rootNode) {
16753             rootNode = newNode
16754         }
16755     }
16756
16757     return rootNode
16758 }
16759
16760 function patchIndices(patches) {
16761     var indices = []
16762
16763     for (var key in patches) {
16764         if (key !== "a") {
16765             indices.push(Number(key))
16766         }
16767     }
16768
16769     return indices
16770 }
16771
16772 },{"./create-element":189,"./dom-index":190,"./patch-op":191,"global/document":16,"x-is-array":228}],193:[function(require,module,exports){
16773 var isWidget = require("../vnode/is-widget.js")
16774
16775 module.exports = updateWidget
16776
16777 function updateWidget(a, b) {
16778     if (isWidget(a) && isWidget(b)) {
16779         if ("name" in a && "name" in b) {
16780             return a.id === b.id
16781         } else {
16782             return a.init === b.init
16783         }
16784     }
16785
16786     return false
16787 }
16788
16789 },{"../vnode/is-widget.js":203}],194:[function(require,module,exports){
16790 'use strict';
16791
16792 var EvStore = require('ev-store');
16793
16794 module.exports = EvHook;
16795
16796 function EvHook(value) {
16797     if (!(this instanceof EvHook)) {
16798         return new EvHook(value);
16799     }
16800
16801     this.value = value;
16802 }
16803
16804 EvHook.prototype.hook = function (node, propertyName) {
16805     var es = EvStore(node);
16806     var propName = propertyName.substr(3);
16807
16808     es[propName] = this.value;
16809 };
16810
16811 EvHook.prototype.unhook = function(node, propertyName) {
16812     var es = EvStore(node);
16813     var propName = propertyName.substr(3);
16814
16815     es[propName] = undefined;
16816 };
16817
16818 },{"ev-store":9}],195:[function(require,module,exports){
16819 'use strict';
16820
16821 module.exports = SoftSetHook;
16822
16823 function SoftSetHook(value) {
16824     if (!(this instanceof SoftSetHook)) {
16825         return new SoftSetHook(value);
16826     }
16827
16828     this.value = value;
16829 }
16830
16831 SoftSetHook.prototype.hook = function (node, propertyName) {
16832     if (node[propertyName] !== this.value) {
16833         node[propertyName] = this.value;
16834     }
16835 };
16836
16837 },{}],196:[function(require,module,exports){
16838 'use strict';
16839
16840 var isArray = require('x-is-array');
16841
16842 var VNode = require('../vnode/vnode.js');
16843 var VText = require('../vnode/vtext.js');
16844 var isVNode = require('../vnode/is-vnode');
16845 var isVText = require('../vnode/is-vtext');
16846 var isWidget = require('../vnode/is-widget');
16847 var isHook = require('../vnode/is-vhook');
16848 var isVThunk = require('../vnode/is-thunk');
16849
16850 var parseTag = require('./parse-tag.js');
16851 var softSetHook = require('./hooks/soft-set-hook.js');
16852 var evHook = require('./hooks/ev-hook.js');
16853
16854 module.exports = h;
16855
16856 function h(tagName, properties, children) {
16857     var childNodes = [];
16858     var tag, props, key, namespace;
16859
16860     if (!children && isChildren(properties)) {
16861         children = properties;
16862         props = {};
16863     }
16864
16865     props = props || properties || {};
16866     tag = parseTag(tagName, props);
16867
16868     // support keys
16869     if (props.hasOwnProperty('key')) {
16870         key = props.key;
16871         props.key = undefined;
16872     }
16873
16874     // support namespace
16875     if (props.hasOwnProperty('namespace')) {
16876         namespace = props.namespace;
16877         props.namespace = undefined;
16878     }
16879
16880     // fix cursor bug
16881     if (tag === 'INPUT' &&
16882         !namespace &&
16883         props.hasOwnProperty('value') &&
16884         props.value !== undefined &&
16885         !isHook(props.value)
16886     ) {
16887         props.value = softSetHook(props.value);
16888     }
16889
16890     transformProperties(props);
16891
16892     if (children !== undefined && children !== null) {
16893         addChild(children, childNodes, tag, props);
16894     }
16895
16896
16897     return new VNode(tag, props, childNodes, key, namespace);
16898 }
16899
16900 function addChild(c, childNodes, tag, props) {
16901     if (typeof c === 'string') {
16902         childNodes.push(new VText(c));
16903     } else if (typeof c === 'number') {
16904         childNodes.push(new VText(String(c)));
16905     } else if (isChild(c)) {
16906         childNodes.push(c);
16907     } else if (isArray(c)) {
16908         for (var i = 0; i < c.length; i++) {
16909             addChild(c[i], childNodes, tag, props);
16910         }
16911     } else if (c === null || c === undefined) {
16912         return;
16913     } else {
16914         throw UnexpectedVirtualElement({
16915             foreignObject: c,
16916             parentVnode: {
16917                 tagName: tag,
16918                 properties: props
16919             }
16920         });
16921     }
16922 }
16923
16924 function transformProperties(props) {
16925     for (var propName in props) {
16926         if (props.hasOwnProperty(propName)) {
16927             var value = props[propName];
16928
16929             if (isHook(value)) {
16930                 continue;
16931             }
16932
16933             if (propName.substr(0, 3) === 'ev-') {
16934                 // add ev-foo support
16935                 props[propName] = evHook(value);
16936             }
16937         }
16938     }
16939 }
16940
16941 function isChild(x) {
16942     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
16943 }
16944
16945 function isChildren(x) {
16946     return typeof x === 'string' || isArray(x) || isChild(x);
16947 }
16948
16949 function UnexpectedVirtualElement(data) {
16950     var err = new Error();
16951
16952     err.type = 'virtual-hyperscript.unexpected.virtual-element';
16953     err.message = 'Unexpected virtual child passed to h().\n' +
16954         'Expected a VNode / Vthunk / VWidget / string but:\n' +
16955         'got:\n' +
16956         errorString(data.foreignObject) +
16957         '.\n' +
16958         'The parent vnode is:\n' +
16959         errorString(data.parentVnode)
16960         '\n' +
16961         'Suggested fix: change your `h(..., [ ... ])` callsite.';
16962     err.foreignObject = data.foreignObject;
16963     err.parentVnode = data.parentVnode;
16964
16965     return err;
16966 }
16967
16968 function errorString(obj) {
16969     try {
16970         return JSON.stringify(obj, null, '    ');
16971     } catch (e) {
16972         return String(obj);
16973     }
16974 }
16975
16976 },{"../vnode/is-thunk":199,"../vnode/is-vhook":200,"../vnode/is-vnode":201,"../vnode/is-vtext":202,"../vnode/is-widget":203,"../vnode/vnode.js":205,"../vnode/vtext.js":207,"./hooks/ev-hook.js":194,"./hooks/soft-set-hook.js":195,"./parse-tag.js":197,"x-is-array":228}],197:[function(require,module,exports){
16977 'use strict';
16978
16979 var split = require('browser-split');
16980
16981 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
16982 var notClassId = /^\.|#/;
16983
16984 module.exports = parseTag;
16985
16986 function parseTag(tag, props) {
16987     if (!tag) {
16988         return 'DIV';
16989     }
16990
16991     var noId = !(props.hasOwnProperty('id'));
16992
16993     var tagParts = split(tag, classIdSplit);
16994     var tagName = null;
16995
16996     if (notClassId.test(tagParts[1])) {
16997         tagName = 'DIV';
16998     }
16999
17000     var classes, part, type, i;
17001
17002     for (i = 0; i < tagParts.length; i++) {
17003         part = tagParts[i];
17004
17005         if (!part) {
17006             continue;
17007         }
17008
17009         type = part.charAt(0);
17010
17011         if (!tagName) {
17012             tagName = part;
17013         } else if (type === '.') {
17014             classes = classes || [];
17015             classes.push(part.substring(1, part.length));
17016         } else if (type === '#' && noId) {
17017             props.id = part.substring(1, part.length);
17018         }
17019     }
17020
17021     if (classes) {
17022         if (props.className) {
17023             classes.push(props.className);
17024         }
17025
17026         props.className = classes.join(' ');
17027     }
17028
17029     return props.namespace ? tagName : tagName.toUpperCase();
17030 }
17031
17032 },{"browser-split":5}],198:[function(require,module,exports){
17033 var isVNode = require("./is-vnode")
17034 var isVText = require("./is-vtext")
17035 var isWidget = require("./is-widget")
17036 var isThunk = require("./is-thunk")
17037
17038 module.exports = handleThunk
17039
17040 function handleThunk(a, b) {
17041     var renderedA = a
17042     var renderedB = b
17043
17044     if (isThunk(b)) {
17045         renderedB = renderThunk(b, a)
17046     }
17047
17048     if (isThunk(a)) {
17049         renderedA = renderThunk(a, null)
17050     }
17051
17052     return {
17053         a: renderedA,
17054         b: renderedB
17055     }
17056 }
17057
17058 function renderThunk(thunk, previous) {
17059     var renderedThunk = thunk.vnode
17060
17061     if (!renderedThunk) {
17062         renderedThunk = thunk.vnode = thunk.render(previous)
17063     }
17064
17065     if (!(isVNode(renderedThunk) ||
17066             isVText(renderedThunk) ||
17067             isWidget(renderedThunk))) {
17068         throw new Error("thunk did not return a valid node");
17069     }
17070
17071     return renderedThunk
17072 }
17073
17074 },{"./is-thunk":199,"./is-vnode":201,"./is-vtext":202,"./is-widget":203}],199:[function(require,module,exports){
17075 module.exports = isThunk
17076
17077 function isThunk(t) {
17078     return t && t.type === "Thunk"
17079 }
17080
17081 },{}],200:[function(require,module,exports){
17082 module.exports = isHook
17083
17084 function isHook(hook) {
17085     return hook &&
17086       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
17087        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
17088 }
17089
17090 },{}],201:[function(require,module,exports){
17091 var version = require("./version")
17092
17093 module.exports = isVirtualNode
17094
17095 function isVirtualNode(x) {
17096     return x && x.type === "VirtualNode" && x.version === version
17097 }
17098
17099 },{"./version":204}],202:[function(require,module,exports){
17100 var version = require("./version")
17101
17102 module.exports = isVirtualText
17103
17104 function isVirtualText(x) {
17105     return x && x.type === "VirtualText" && x.version === version
17106 }
17107
17108 },{"./version":204}],203:[function(require,module,exports){
17109 module.exports = isWidget
17110
17111 function isWidget(w) {
17112     return w && w.type === "Widget"
17113 }
17114
17115 },{}],204:[function(require,module,exports){
17116 module.exports = "2"
17117
17118 },{}],205:[function(require,module,exports){
17119 var version = require("./version")
17120 var isVNode = require("./is-vnode")
17121 var isWidget = require("./is-widget")
17122 var isThunk = require("./is-thunk")
17123 var isVHook = require("./is-vhook")
17124
17125 module.exports = VirtualNode
17126
17127 var noProperties = {}
17128 var noChildren = []
17129
17130 function VirtualNode(tagName, properties, children, key, namespace) {
17131     this.tagName = tagName
17132     this.properties = properties || noProperties
17133     this.children = children || noChildren
17134     this.key = key != null ? String(key) : undefined
17135     this.namespace = (typeof namespace === "string") ? namespace : null
17136
17137     var count = (children && children.length) || 0
17138     var descendants = 0
17139     var hasWidgets = false
17140     var hasThunks = false
17141     var descendantHooks = false
17142     var hooks
17143
17144     for (var propName in properties) {
17145         if (properties.hasOwnProperty(propName)) {
17146             var property = properties[propName]
17147             if (isVHook(property) && property.unhook) {
17148                 if (!hooks) {
17149                     hooks = {}
17150                 }
17151
17152                 hooks[propName] = property
17153             }
17154         }
17155     }
17156
17157     for (var i = 0; i < count; i++) {
17158         var child = children[i]
17159         if (isVNode(child)) {
17160             descendants += child.count || 0
17161
17162             if (!hasWidgets && child.hasWidgets) {
17163                 hasWidgets = true
17164             }
17165
17166             if (!hasThunks && child.hasThunks) {
17167                 hasThunks = true
17168             }
17169
17170             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
17171                 descendantHooks = true
17172             }
17173         } else if (!hasWidgets && isWidget(child)) {
17174             if (typeof child.destroy === "function") {
17175                 hasWidgets = true
17176             }
17177         } else if (!hasThunks && isThunk(child)) {
17178             hasThunks = true;
17179         }
17180     }
17181
17182     this.count = count + descendants
17183     this.hasWidgets = hasWidgets
17184     this.hasThunks = hasThunks
17185     this.hooks = hooks
17186     this.descendantHooks = descendantHooks
17187 }
17188
17189 VirtualNode.prototype.version = version
17190 VirtualNode.prototype.type = "VirtualNode"
17191
17192 },{"./is-thunk":199,"./is-vhook":200,"./is-vnode":201,"./is-widget":203,"./version":204}],206:[function(require,module,exports){
17193 var version = require("./version")
17194
17195 VirtualPatch.NONE = 0
17196 VirtualPatch.VTEXT = 1
17197 VirtualPatch.VNODE = 2
17198 VirtualPatch.WIDGET = 3
17199 VirtualPatch.PROPS = 4
17200 VirtualPatch.ORDER = 5
17201 VirtualPatch.INSERT = 6
17202 VirtualPatch.REMOVE = 7
17203 VirtualPatch.THUNK = 8
17204
17205 module.exports = VirtualPatch
17206
17207 function VirtualPatch(type, vNode, patch) {
17208     this.type = Number(type)
17209     this.vNode = vNode
17210     this.patch = patch
17211 }
17212
17213 VirtualPatch.prototype.version = version
17214 VirtualPatch.prototype.type = "VirtualPatch"
17215
17216 },{"./version":204}],207:[function(require,module,exports){
17217 var version = require("./version")
17218
17219 module.exports = VirtualText
17220
17221 function VirtualText(text) {
17222     this.text = String(text)
17223 }
17224
17225 VirtualText.prototype.version = version
17226 VirtualText.prototype.type = "VirtualText"
17227
17228 },{"./version":204}],208:[function(require,module,exports){
17229 var isObject = require("is-object")
17230 var isHook = require("../vnode/is-vhook")
17231
17232 module.exports = diffProps
17233
17234 function diffProps(a, b) {
17235     var diff
17236
17237     for (var aKey in a) {
17238         if (!(aKey in b)) {
17239             diff = diff || {}
17240             diff[aKey] = undefined
17241         }
17242
17243         var aValue = a[aKey]
17244         var bValue = b[aKey]
17245
17246         if (aValue === bValue) {
17247             continue
17248         } else if (isObject(aValue) && isObject(bValue)) {
17249             if (getPrototype(bValue) !== getPrototype(aValue)) {
17250                 diff = diff || {}
17251                 diff[aKey] = bValue
17252             } else if (isHook(bValue)) {
17253                  diff = diff || {}
17254                  diff[aKey] = bValue
17255             } else {
17256                 var objectDiff = diffProps(aValue, bValue)
17257                 if (objectDiff) {
17258                     diff = diff || {}
17259                     diff[aKey] = objectDiff
17260                 }
17261             }
17262         } else {
17263             diff = diff || {}
17264             diff[aKey] = bValue
17265         }
17266     }
17267
17268     for (var bKey in b) {
17269         if (!(bKey in a)) {
17270             diff = diff || {}
17271             diff[bKey] = b[bKey]
17272         }
17273     }
17274
17275     return diff
17276 }
17277
17278 function getPrototype(value) {
17279   if (Object.getPrototypeOf) {
17280     return Object.getPrototypeOf(value)
17281   } else if (value.__proto__) {
17282     return value.__proto__
17283   } else if (value.constructor) {
17284     return value.constructor.prototype
17285   }
17286 }
17287
17288 },{"../vnode/is-vhook":200,"is-object":20}],209:[function(require,module,exports){
17289 var isArray = require("x-is-array")
17290
17291 var VPatch = require("../vnode/vpatch")
17292 var isVNode = require("../vnode/is-vnode")
17293 var isVText = require("../vnode/is-vtext")
17294 var isWidget = require("../vnode/is-widget")
17295 var isThunk = require("../vnode/is-thunk")
17296 var handleThunk = require("../vnode/handle-thunk")
17297
17298 var diffProps = require("./diff-props")
17299
17300 module.exports = diff
17301
17302 function diff(a, b) {
17303     var patch = { a: a }
17304     walk(a, b, patch, 0)
17305     return patch
17306 }
17307
17308 function walk(a, b, patch, index) {
17309     if (a === b) {
17310         return
17311     }
17312
17313     var apply = patch[index]
17314     var applyClear = false
17315
17316     if (isThunk(a) || isThunk(b)) {
17317         thunks(a, b, patch, index)
17318     } else if (b == null) {
17319
17320         // If a is a widget we will add a remove patch for it
17321         // Otherwise any child widgets/hooks must be destroyed.
17322         // This prevents adding two remove patches for a widget.
17323         if (!isWidget(a)) {
17324             clearState(a, patch, index)
17325             apply = patch[index]
17326         }
17327
17328         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
17329     } else if (isVNode(b)) {
17330         if (isVNode(a)) {
17331             if (a.tagName === b.tagName &&
17332                 a.namespace === b.namespace &&
17333                 a.key === b.key) {
17334                 var propsPatch = diffProps(a.properties, b.properties)
17335                 if (propsPatch) {
17336                     apply = appendPatch(apply,
17337                         new VPatch(VPatch.PROPS, a, propsPatch))
17338                 }
17339                 apply = diffChildren(a, b, patch, apply, index)
17340             } else {
17341                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17342                 applyClear = true
17343             }
17344         } else {
17345             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17346             applyClear = true
17347         }
17348     } else if (isVText(b)) {
17349         if (!isVText(a)) {
17350             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17351             applyClear = true
17352         } else if (a.text !== b.text) {
17353             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17354         }
17355     } else if (isWidget(b)) {
17356         if (!isWidget(a)) {
17357             applyClear = true
17358         }
17359
17360         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
17361     }
17362
17363     if (apply) {
17364         patch[index] = apply
17365     }
17366
17367     if (applyClear) {
17368         clearState(a, patch, index)
17369     }
17370 }
17371
17372 function diffChildren(a, b, patch, apply, index) {
17373     var aChildren = a.children
17374     var orderedSet = reorder(aChildren, b.children)
17375     var bChildren = orderedSet.children
17376
17377     var aLen = aChildren.length
17378     var bLen = bChildren.length
17379     var len = aLen > bLen ? aLen : bLen
17380
17381     for (var i = 0; i < len; i++) {
17382         var leftNode = aChildren[i]
17383         var rightNode = bChildren[i]
17384         index += 1
17385
17386         if (!leftNode) {
17387             if (rightNode) {
17388                 // Excess nodes in b need to be added
17389                 apply = appendPatch(apply,
17390                     new VPatch(VPatch.INSERT, null, rightNode))
17391             }
17392         } else {
17393             walk(leftNode, rightNode, patch, index)
17394         }
17395
17396         if (isVNode(leftNode) && leftNode.count) {
17397             index += leftNode.count
17398         }
17399     }
17400
17401     if (orderedSet.moves) {
17402         // Reorder nodes last
17403         apply = appendPatch(apply, new VPatch(
17404             VPatch.ORDER,
17405             a,
17406             orderedSet.moves
17407         ))
17408     }
17409
17410     return apply
17411 }
17412
17413 function clearState(vNode, patch, index) {
17414     // TODO: Make this a single walk, not two
17415     unhook(vNode, patch, index)
17416     destroyWidgets(vNode, patch, index)
17417 }
17418
17419 // Patch records for all destroyed widgets must be added because we need
17420 // a DOM node reference for the destroy function
17421 function destroyWidgets(vNode, patch, index) {
17422     if (isWidget(vNode)) {
17423         if (typeof vNode.destroy === "function") {
17424             patch[index] = appendPatch(
17425                 patch[index],
17426                 new VPatch(VPatch.REMOVE, vNode, null)
17427             )
17428         }
17429     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
17430         var children = vNode.children
17431         var len = children.length
17432         for (var i = 0; i < len; i++) {
17433             var child = children[i]
17434             index += 1
17435
17436             destroyWidgets(child, patch, index)
17437
17438             if (isVNode(child) && child.count) {
17439                 index += child.count
17440             }
17441         }
17442     } else if (isThunk(vNode)) {
17443         thunks(vNode, null, patch, index)
17444     }
17445 }
17446
17447 // Create a sub-patch for thunks
17448 function thunks(a, b, patch, index) {
17449     var nodes = handleThunk(a, b)
17450     var thunkPatch = diff(nodes.a, nodes.b)
17451     if (hasPatches(thunkPatch)) {
17452         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
17453     }
17454 }
17455
17456 function hasPatches(patch) {
17457     for (var index in patch) {
17458         if (index !== "a") {
17459             return true
17460         }
17461     }
17462
17463     return false
17464 }
17465
17466 // Execute hooks when two nodes are identical
17467 function unhook(vNode, patch, index) {
17468     if (isVNode(vNode)) {
17469         if (vNode.hooks) {
17470             patch[index] = appendPatch(
17471                 patch[index],
17472                 new VPatch(
17473                     VPatch.PROPS,
17474                     vNode,
17475                     undefinedKeys(vNode.hooks)
17476                 )
17477             )
17478         }
17479
17480         if (vNode.descendantHooks || vNode.hasThunks) {
17481             var children = vNode.children
17482             var len = children.length
17483             for (var i = 0; i < len; i++) {
17484                 var child = children[i]
17485                 index += 1
17486
17487                 unhook(child, patch, index)
17488
17489                 if (isVNode(child) && child.count) {
17490                     index += child.count
17491                 }
17492             }
17493         }
17494     } else if (isThunk(vNode)) {
17495         thunks(vNode, null, patch, index)
17496     }
17497 }
17498
17499 function undefinedKeys(obj) {
17500     var result = {}
17501
17502     for (var key in obj) {
17503         result[key] = undefined
17504     }
17505
17506     return result
17507 }
17508
17509 // List diff, naive left to right reordering
17510 function reorder(aChildren, bChildren) {
17511     // O(M) time, O(M) memory
17512     var bChildIndex = keyIndex(bChildren)
17513     var bKeys = bChildIndex.keys
17514     var bFree = bChildIndex.free
17515
17516     if (bFree.length === bChildren.length) {
17517         return {
17518             children: bChildren,
17519             moves: null
17520         }
17521     }
17522
17523     // O(N) time, O(N) memory
17524     var aChildIndex = keyIndex(aChildren)
17525     var aKeys = aChildIndex.keys
17526     var aFree = aChildIndex.free
17527
17528     if (aFree.length === aChildren.length) {
17529         return {
17530             children: bChildren,
17531             moves: null
17532         }
17533     }
17534
17535     // O(MAX(N, M)) memory
17536     var newChildren = []
17537
17538     var freeIndex = 0
17539     var freeCount = bFree.length
17540     var deletedItems = 0
17541
17542     // Iterate through a and match a node in b
17543     // O(N) time,
17544     for (var i = 0 ; i < aChildren.length; i++) {
17545         var aItem = aChildren[i]
17546         var itemIndex
17547
17548         if (aItem.key) {
17549             if (bKeys.hasOwnProperty(aItem.key)) {
17550                 // Match up the old keys
17551                 itemIndex = bKeys[aItem.key]
17552                 newChildren.push(bChildren[itemIndex])
17553
17554             } else {
17555                 // Remove old keyed items
17556                 itemIndex = i - deletedItems++
17557                 newChildren.push(null)
17558             }
17559         } else {
17560             // Match the item in a with the next free item in b
17561             if (freeIndex < freeCount) {
17562                 itemIndex = bFree[freeIndex++]
17563                 newChildren.push(bChildren[itemIndex])
17564             } else {
17565                 // There are no free items in b to match with
17566                 // the free items in a, so the extra free nodes
17567                 // are deleted.
17568                 itemIndex = i - deletedItems++
17569                 newChildren.push(null)
17570             }
17571         }
17572     }
17573
17574     var lastFreeIndex = freeIndex >= bFree.length ?
17575         bChildren.length :
17576         bFree[freeIndex]
17577
17578     // Iterate through b and append any new keys
17579     // O(M) time
17580     for (var j = 0; j < bChildren.length; j++) {
17581         var newItem = bChildren[j]
17582
17583         if (newItem.key) {
17584             if (!aKeys.hasOwnProperty(newItem.key)) {
17585                 // Add any new keyed items
17586                 // We are adding new items to the end and then sorting them
17587                 // in place. In future we should insert new items in place.
17588                 newChildren.push(newItem)
17589             }
17590         } else if (j >= lastFreeIndex) {
17591             // Add any leftover non-keyed items
17592             newChildren.push(newItem)
17593         }
17594     }
17595
17596     var simulate = newChildren.slice()
17597     var simulateIndex = 0
17598     var removes = []
17599     var inserts = []
17600     var simulateItem
17601
17602     for (var k = 0; k < bChildren.length;) {
17603         var wantedItem = bChildren[k]
17604         simulateItem = simulate[simulateIndex]
17605
17606         // remove items
17607         while (simulateItem === null && simulate.length) {
17608             removes.push(remove(simulate, simulateIndex, null))
17609             simulateItem = simulate[simulateIndex]
17610         }
17611
17612         if (!simulateItem || simulateItem.key !== wantedItem.key) {
17613             // if we need a key in this position...
17614             if (wantedItem.key) {
17615                 if (simulateItem && simulateItem.key) {
17616                     // if an insert doesn't put this key in place, it needs to move
17617                     if (bKeys[simulateItem.key] !== k + 1) {
17618                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
17619                         simulateItem = simulate[simulateIndex]
17620                         // if the remove didn't put the wanted item in place, we need to insert it
17621                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
17622                             inserts.push({key: wantedItem.key, to: k})
17623                         }
17624                         // items are matching, so skip ahead
17625                         else {
17626                             simulateIndex++
17627                         }
17628                     }
17629                     else {
17630                         inserts.push({key: wantedItem.key, to: k})
17631                     }
17632                 }
17633                 else {
17634                     inserts.push({key: wantedItem.key, to: k})
17635                 }
17636                 k++
17637             }
17638             // a key in simulate has no matching wanted key, remove it
17639             else if (simulateItem && simulateItem.key) {
17640                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17641             }
17642         }
17643         else {
17644             simulateIndex++
17645             k++
17646         }
17647     }
17648
17649     // remove all the remaining nodes from simulate
17650     while(simulateIndex < simulate.length) {
17651         simulateItem = simulate[simulateIndex]
17652         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
17653     }
17654
17655     // If the only moves we have are deletes then we can just
17656     // let the delete patch remove these items.
17657     if (removes.length === deletedItems && !inserts.length) {
17658         return {
17659             children: newChildren,
17660             moves: null
17661         }
17662     }
17663
17664     return {
17665         children: newChildren,
17666         moves: {
17667             removes: removes,
17668             inserts: inserts
17669         }
17670     }
17671 }
17672
17673 function remove(arr, index, key) {
17674     arr.splice(index, 1)
17675
17676     return {
17677         from: index,
17678         key: key
17679     }
17680 }
17681
17682 function keyIndex(children) {
17683     var keys = {}
17684     var free = []
17685     var length = children.length
17686
17687     for (var i = 0; i < length; i++) {
17688         var child = children[i]
17689
17690         if (child.key) {
17691             keys[child.key] = i
17692         } else {
17693             free.push(i)
17694         }
17695     }
17696
17697     return {
17698         keys: keys,     // A hash of key name to index
17699         free: free      // An array of unkeyed item indices
17700     }
17701 }
17702
17703 function appendPatch(apply, patch) {
17704     if (apply) {
17705         if (isArray(apply)) {
17706             apply.push(patch)
17707         } else {
17708             apply = [apply, patch]
17709         }
17710
17711         return apply
17712     } else {
17713         return patch
17714     }
17715 }
17716
17717 },{"../vnode/handle-thunk":198,"../vnode/is-thunk":199,"../vnode/is-vnode":201,"../vnode/is-vtext":202,"../vnode/is-widget":203,"../vnode/vpatch":206,"./diff-props":208,"x-is-array":228}],210:[function(require,module,exports){
17718 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17719 /** @author Brian Cavalier */
17720 /** @author John Hann */
17721
17722 (function(define) { 'use strict';
17723 define(function (require) {
17724
17725         var makePromise = require('./makePromise');
17726         var Scheduler = require('./Scheduler');
17727         var async = require('./env').asap;
17728
17729         return makePromise({
17730                 scheduler: new Scheduler(async)
17731         });
17732
17733 });
17734 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
17735
17736 },{"./Scheduler":211,"./env":223,"./makePromise":225}],211:[function(require,module,exports){
17737 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17738 /** @author Brian Cavalier */
17739 /** @author John Hann */
17740
17741 (function(define) { 'use strict';
17742 define(function() {
17743
17744         // Credit to Twisol (https://github.com/Twisol) for suggesting
17745         // this type of extensible queue + trampoline approach for next-tick conflation.
17746
17747         /**
17748          * Async task scheduler
17749          * @param {function} async function to schedule a single async function
17750          * @constructor
17751          */
17752         function Scheduler(async) {
17753                 this._async = async;
17754                 this._running = false;
17755
17756                 this._queue = this;
17757                 this._queueLen = 0;
17758                 this._afterQueue = {};
17759                 this._afterQueueLen = 0;
17760
17761                 var self = this;
17762                 this.drain = function() {
17763                         self._drain();
17764                 };
17765         }
17766
17767         /**
17768          * Enqueue a task
17769          * @param {{ run:function }} task
17770          */
17771         Scheduler.prototype.enqueue = function(task) {
17772                 this._queue[this._queueLen++] = task;
17773                 this.run();
17774         };
17775
17776         /**
17777          * Enqueue a task to run after the main task queue
17778          * @param {{ run:function }} task
17779          */
17780         Scheduler.prototype.afterQueue = function(task) {
17781                 this._afterQueue[this._afterQueueLen++] = task;
17782                 this.run();
17783         };
17784
17785         Scheduler.prototype.run = function() {
17786                 if (!this._running) {
17787                         this._running = true;
17788                         this._async(this.drain);
17789                 }
17790         };
17791
17792         /**
17793          * Drain the handler queue entirely, and then the after queue
17794          */
17795         Scheduler.prototype._drain = function() {
17796                 var i = 0;
17797                 for (; i < this._queueLen; ++i) {
17798                         this._queue[i].run();
17799                         this._queue[i] = void 0;
17800                 }
17801
17802                 this._queueLen = 0;
17803                 this._running = false;
17804
17805                 for (i = 0; i < this._afterQueueLen; ++i) {
17806                         this._afterQueue[i].run();
17807                         this._afterQueue[i] = void 0;
17808                 }
17809
17810                 this._afterQueueLen = 0;
17811         };
17812
17813         return Scheduler;
17814
17815 });
17816 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17817
17818 },{}],212:[function(require,module,exports){
17819 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17820 /** @author Brian Cavalier */
17821 /** @author John Hann */
17822
17823 (function(define) { 'use strict';
17824 define(function() {
17825
17826         /**
17827          * Custom error type for promises rejected by promise.timeout
17828          * @param {string} message
17829          * @constructor
17830          */
17831         function TimeoutError (message) {
17832                 Error.call(this);
17833                 this.message = message;
17834                 this.name = TimeoutError.name;
17835                 if (typeof Error.captureStackTrace === 'function') {
17836                         Error.captureStackTrace(this, TimeoutError);
17837                 }
17838         }
17839
17840         TimeoutError.prototype = Object.create(Error.prototype);
17841         TimeoutError.prototype.constructor = TimeoutError;
17842
17843         return TimeoutError;
17844 });
17845 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17846 },{}],213:[function(require,module,exports){
17847 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17848 /** @author Brian Cavalier */
17849 /** @author John Hann */
17850
17851 (function(define) { 'use strict';
17852 define(function() {
17853
17854         makeApply.tryCatchResolve = tryCatchResolve;
17855
17856         return makeApply;
17857
17858         function makeApply(Promise, call) {
17859                 if(arguments.length < 2) {
17860                         call = tryCatchResolve;
17861                 }
17862
17863                 return apply;
17864
17865                 function apply(f, thisArg, args) {
17866                         var p = Promise._defer();
17867                         var l = args.length;
17868                         var params = new Array(l);
17869                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
17870
17871                         return p;
17872                 }
17873
17874                 function callAndResolve(c, h) {
17875                         if(c.i < 0) {
17876                                 return call(c.f, c.thisArg, c.params, h);
17877                         }
17878
17879                         var handler = Promise._handler(c.args[c.i]);
17880                         handler.fold(callAndResolveNext, c, void 0, h);
17881                 }
17882
17883                 function callAndResolveNext(c, x, h) {
17884                         c.params[c.i] = x;
17885                         c.i -= 1;
17886                         callAndResolve(c, h);
17887                 }
17888         }
17889
17890         function tryCatchResolve(f, thisArg, args, resolver) {
17891                 try {
17892                         resolver.resolve(f.apply(thisArg, args));
17893                 } catch(e) {
17894                         resolver.reject(e);
17895                 }
17896         }
17897
17898 });
17899 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17900
17901
17902
17903 },{}],214:[function(require,module,exports){
17904 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17905 /** @author Brian Cavalier */
17906 /** @author John Hann */
17907
17908 (function(define) { 'use strict';
17909 define(function(require) {
17910
17911         var state = require('../state');
17912         var applier = require('../apply');
17913
17914         return function array(Promise) {
17915
17916                 var applyFold = applier(Promise);
17917                 var toPromise = Promise.resolve;
17918                 var all = Promise.all;
17919
17920                 var ar = Array.prototype.reduce;
17921                 var arr = Array.prototype.reduceRight;
17922                 var slice = Array.prototype.slice;
17923
17924                 // Additional array combinators
17925
17926                 Promise.any = any;
17927                 Promise.some = some;
17928                 Promise.settle = settle;
17929
17930                 Promise.map = map;
17931                 Promise.filter = filter;
17932                 Promise.reduce = reduce;
17933                 Promise.reduceRight = reduceRight;
17934
17935                 /**
17936                  * When this promise fulfills with an array, do
17937                  * onFulfilled.apply(void 0, array)
17938                  * @param {function} onFulfilled function to apply
17939                  * @returns {Promise} promise for the result of applying onFulfilled
17940                  */
17941                 Promise.prototype.spread = function(onFulfilled) {
17942                         return this.then(all).then(function(array) {
17943                                 return onFulfilled.apply(this, array);
17944                         });
17945                 };
17946
17947                 return Promise;
17948
17949                 /**
17950                  * One-winner competitive race.
17951                  * Return a promise that will fulfill when one of the promises
17952                  * in the input array fulfills, or will reject when all promises
17953                  * have rejected.
17954                  * @param {array} promises
17955                  * @returns {Promise} promise for the first fulfilled value
17956                  */
17957                 function any(promises) {
17958                         var p = Promise._defer();
17959                         var resolver = p._handler;
17960                         var l = promises.length>>>0;
17961
17962                         var pending = l;
17963                         var errors = [];
17964
17965                         for (var h, x, i = 0; i < l; ++i) {
17966                                 x = promises[i];
17967                                 if(x === void 0 && !(i in promises)) {
17968                                         --pending;
17969                                         continue;
17970                                 }
17971
17972                                 h = Promise._handler(x);
17973                                 if(h.state() > 0) {
17974                                         resolver.become(h);
17975                                         Promise._visitRemaining(promises, i, h);
17976                                         break;
17977                                 } else {
17978                                         h.visit(resolver, handleFulfill, handleReject);
17979                                 }
17980                         }
17981
17982                         if(pending === 0) {
17983                                 resolver.reject(new RangeError('any(): array must not be empty'));
17984                         }
17985
17986                         return p;
17987
17988                         function handleFulfill(x) {
17989                                 /*jshint validthis:true*/
17990                                 errors = null;
17991                                 this.resolve(x); // this === resolver
17992                         }
17993
17994                         function handleReject(e) {
17995                                 /*jshint validthis:true*/
17996                                 if(this.resolved) { // this === resolver
17997                                         return;
17998                                 }
17999
18000                                 errors.push(e);
18001                                 if(--pending === 0) {
18002                                         this.reject(errors);
18003                                 }
18004                         }
18005                 }
18006
18007                 /**
18008                  * N-winner competitive race
18009                  * Return a promise that will fulfill when n input promises have
18010                  * fulfilled, or will reject when it becomes impossible for n
18011                  * input promises to fulfill (ie when promises.length - n + 1
18012                  * have rejected)
18013                  * @param {array} promises
18014                  * @param {number} n
18015                  * @returns {Promise} promise for the earliest n fulfillment values
18016                  *
18017                  * @deprecated
18018                  */
18019                 function some(promises, n) {
18020                         /*jshint maxcomplexity:7*/
18021                         var p = Promise._defer();
18022                         var resolver = p._handler;
18023
18024                         var results = [];
18025                         var errors = [];
18026
18027                         var l = promises.length>>>0;
18028                         var nFulfill = 0;
18029                         var nReject;
18030                         var x, i; // reused in both for() loops
18031
18032                         // First pass: count actual array items
18033                         for(i=0; i<l; ++i) {
18034                                 x = promises[i];
18035                                 if(x === void 0 && !(i in promises)) {
18036                                         continue;
18037                                 }
18038                                 ++nFulfill;
18039                         }
18040
18041                         // Compute actual goals
18042                         n = Math.max(n, 0);
18043                         nReject = (nFulfill - n + 1);
18044                         nFulfill = Math.min(n, nFulfill);
18045
18046                         if(n > nFulfill) {
18047                                 resolver.reject(new RangeError('some(): array must contain at least '
18048                                 + n + ' item(s), but had ' + nFulfill));
18049                         } else if(nFulfill === 0) {
18050                                 resolver.resolve(results);
18051                         }
18052
18053                         // Second pass: observe each array item, make progress toward goals
18054                         for(i=0; i<l; ++i) {
18055                                 x = promises[i];
18056                                 if(x === void 0 && !(i in promises)) {
18057                                         continue;
18058                                 }
18059
18060                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
18061                         }
18062
18063                         return p;
18064
18065                         function fulfill(x) {
18066                                 /*jshint validthis:true*/
18067                                 if(this.resolved) { // this === resolver
18068                                         return;
18069                                 }
18070
18071                                 results.push(x);
18072                                 if(--nFulfill === 0) {
18073                                         errors = null;
18074                                         this.resolve(results);
18075                                 }
18076                         }
18077
18078                         function reject(e) {
18079                                 /*jshint validthis:true*/
18080                                 if(this.resolved) { // this === resolver
18081                                         return;
18082                                 }
18083
18084                                 errors.push(e);
18085                                 if(--nReject === 0) {
18086                                         results = null;
18087                                         this.reject(errors);
18088                                 }
18089                         }
18090                 }
18091
18092                 /**
18093                  * Apply f to the value of each promise in a list of promises
18094                  * and return a new list containing the results.
18095                  * @param {array} promises
18096                  * @param {function(x:*, index:Number):*} f mapping function
18097                  * @returns {Promise}
18098                  */
18099                 function map(promises, f) {
18100                         return Promise._traverse(f, promises);
18101                 }
18102
18103                 /**
18104                  * Filter the provided array of promises using the provided predicate.  Input may
18105                  * contain promises and values
18106                  * @param {Array} promises array of promises and values
18107                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
18108                  *  Must return truthy (or promise for truthy) for items to retain.
18109                  * @returns {Promise} promise that will fulfill with an array containing all items
18110                  *  for which predicate returned truthy.
18111                  */
18112                 function filter(promises, predicate) {
18113                         var a = slice.call(promises);
18114                         return Promise._traverse(predicate, a).then(function(keep) {
18115                                 return filterSync(a, keep);
18116                         });
18117                 }
18118
18119                 function filterSync(promises, keep) {
18120                         // Safe because we know all promises have fulfilled if we've made it this far
18121                         var l = keep.length;
18122                         var filtered = new Array(l);
18123                         for(var i=0, j=0; i<l; ++i) {
18124                                 if(keep[i]) {
18125                                         filtered[j++] = Promise._handler(promises[i]).value;
18126                                 }
18127                         }
18128                         filtered.length = j;
18129                         return filtered;
18130
18131                 }
18132
18133                 /**
18134                  * Return a promise that will always fulfill with an array containing
18135                  * the outcome states of all input promises.  The returned promise
18136                  * will never reject.
18137                  * @param {Array} promises
18138                  * @returns {Promise} promise for array of settled state descriptors
18139                  */
18140                 function settle(promises) {
18141                         return all(promises.map(settleOne));
18142                 }
18143
18144                 function settleOne(p) {
18145                         // Optimize the case where we get an already-resolved when.js promise
18146                         //  by extracting its state:
18147                         var handler;
18148                         if (p instanceof Promise) {
18149                                 // This is our own Promise type and we can reach its handler internals:
18150                                 handler = p._handler.join();
18151                         }
18152                         if((handler && handler.state() === 0) || !handler) {
18153                                 // Either still pending, or not a Promise at all:
18154                                 return toPromise(p).then(state.fulfilled, state.rejected);
18155                         }
18156
18157                         // The promise is our own, but it is already resolved. Take a shortcut.
18158                         // Since we're not actually handling the resolution, we need to disable
18159                         // rejection reporting.
18160                         handler._unreport();
18161                         return state.inspect(handler);
18162                 }
18163
18164                 /**
18165                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
18166                  * input may contain promises and/or values, and reduceFunc
18167                  * may return either a value or a promise, *and* initialValue may
18168                  * be a promise for the starting value.
18169                  * @param {Array|Promise} promises array or promise for an array of anything,
18170                  *      may contain a mix of promises and values.
18171                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
18172                  * @returns {Promise} that will resolve to the final reduced value
18173                  */
18174                 function reduce(promises, f /*, initialValue */) {
18175                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
18176                                         : ar.call(promises, liftCombine(f));
18177                 }
18178
18179                 /**
18180                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
18181                  * input may contain promises and/or values, and reduceFunc
18182                  * may return either a value or a promise, *and* initialValue may
18183                  * be a promise for the starting value.
18184                  * @param {Array|Promise} promises array or promise for an array of anything,
18185                  *      may contain a mix of promises and values.
18186                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
18187                  * @returns {Promise} that will resolve to the final reduced value
18188                  */
18189                 function reduceRight(promises, f /*, initialValue */) {
18190                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
18191                                         : arr.call(promises, liftCombine(f));
18192                 }
18193
18194                 function liftCombine(f) {
18195                         return function(z, x, i) {
18196                                 return applyFold(f, void 0, [z,x,i]);
18197                         };
18198                 }
18199         };
18200
18201 });
18202 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18203
18204 },{"../apply":213,"../state":226}],215:[function(require,module,exports){
18205 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18206 /** @author Brian Cavalier */
18207 /** @author John Hann */
18208
18209 (function(define) { 'use strict';
18210 define(function() {
18211
18212         return function flow(Promise) {
18213
18214                 var resolve = Promise.resolve;
18215                 var reject = Promise.reject;
18216                 var origCatch = Promise.prototype['catch'];
18217
18218                 /**
18219                  * Handle the ultimate fulfillment value or rejection reason, and assume
18220                  * responsibility for all errors.  If an error propagates out of result
18221                  * or handleFatalError, it will be rethrown to the host, resulting in a
18222                  * loud stack track on most platforms and a crash on some.
18223                  * @param {function?} onResult
18224                  * @param {function?} onError
18225                  * @returns {undefined}
18226                  */
18227                 Promise.prototype.done = function(onResult, onError) {
18228                         this._handler.visit(this._handler.receiver, onResult, onError);
18229                 };
18230
18231                 /**
18232                  * Add Error-type and predicate matching to catch.  Examples:
18233                  * promise.catch(TypeError, handleTypeError)
18234                  *   .catch(predicate, handleMatchedErrors)
18235                  *   .catch(handleRemainingErrors)
18236                  * @param onRejected
18237                  * @returns {*}
18238                  */
18239                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
18240                         if (arguments.length < 2) {
18241                                 return origCatch.call(this, onRejected);
18242                         }
18243
18244                         if(typeof onRejected !== 'function') {
18245                                 return this.ensure(rejectInvalidPredicate);
18246                         }
18247
18248                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
18249                 };
18250
18251                 /**
18252                  * Wraps the provided catch handler, so that it will only be called
18253                  * if the predicate evaluates truthy
18254                  * @param {?function} handler
18255                  * @param {function} predicate
18256                  * @returns {function} conditional catch handler
18257                  */
18258                 function createCatchFilter(handler, predicate) {
18259                         return function(e) {
18260                                 return evaluatePredicate(e, predicate)
18261                                         ? handler.call(this, e)
18262                                         : reject(e);
18263                         };
18264                 }
18265
18266                 /**
18267                  * Ensures that onFulfilledOrRejected will be called regardless of whether
18268                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
18269                  * receive the promises' value or reason.  Any returned value will be disregarded.
18270                  * onFulfilledOrRejected may throw or return a rejected promise to signal
18271                  * an additional error.
18272                  * @param {function} handler handler to be called regardless of
18273                  *  fulfillment or rejection
18274                  * @returns {Promise}
18275                  */
18276                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
18277                         if(typeof handler !== 'function') {
18278                                 return this;
18279                         }
18280
18281                         return this.then(function(x) {
18282                                 return runSideEffect(handler, this, identity, x);
18283                         }, function(e) {
18284                                 return runSideEffect(handler, this, reject, e);
18285                         });
18286                 };
18287
18288                 function runSideEffect (handler, thisArg, propagate, value) {
18289                         var result = handler.call(thisArg);
18290                         return maybeThenable(result)
18291                                 ? propagateValue(result, propagate, value)
18292                                 : propagate(value);
18293                 }
18294
18295                 function propagateValue (result, propagate, x) {
18296                         return resolve(result).then(function () {
18297                                 return propagate(x);
18298                         });
18299                 }
18300
18301                 /**
18302                  * Recover from a failure by returning a defaultValue.  If defaultValue
18303                  * is a promise, it's fulfillment value will be used.  If defaultValue is
18304                  * a promise that rejects, the returned promise will reject with the
18305                  * same reason.
18306                  * @param {*} defaultValue
18307                  * @returns {Promise} new promise
18308                  */
18309                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
18310                         return this.then(void 0, function() {
18311                                 return defaultValue;
18312                         });
18313                 };
18314
18315                 /**
18316                  * Shortcut for .then(function() { return value; })
18317                  * @param  {*} value
18318                  * @return {Promise} a promise that:
18319                  *  - is fulfilled if value is not a promise, or
18320                  *  - if value is a promise, will fulfill with its value, or reject
18321                  *    with its reason.
18322                  */
18323                 Promise.prototype['yield'] = function(value) {
18324                         return this.then(function() {
18325                                 return value;
18326                         });
18327                 };
18328
18329                 /**
18330                  * Runs a side effect when this promise fulfills, without changing the
18331                  * fulfillment value.
18332                  * @param {function} onFulfilledSideEffect
18333                  * @returns {Promise}
18334                  */
18335                 Promise.prototype.tap = function(onFulfilledSideEffect) {
18336                         return this.then(onFulfilledSideEffect)['yield'](this);
18337                 };
18338
18339                 return Promise;
18340         };
18341
18342         function rejectInvalidPredicate() {
18343                 throw new TypeError('catch predicate must be a function');
18344         }
18345
18346         function evaluatePredicate(e, predicate) {
18347                 return isError(predicate) ? e instanceof predicate : predicate(e);
18348         }
18349
18350         function isError(predicate) {
18351                 return predicate === Error
18352                         || (predicate != null && predicate.prototype instanceof Error);
18353         }
18354
18355         function maybeThenable(x) {
18356                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
18357         }
18358
18359         function identity(x) {
18360                 return x;
18361         }
18362
18363 });
18364 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18365
18366 },{}],216:[function(require,module,exports){
18367 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18368 /** @author Brian Cavalier */
18369 /** @author John Hann */
18370 /** @author Jeff Escalante */
18371
18372 (function(define) { 'use strict';
18373 define(function() {
18374
18375         return function fold(Promise) {
18376
18377                 Promise.prototype.fold = function(f, z) {
18378                         var promise = this._beget();
18379
18380                         this._handler.fold(function(z, x, to) {
18381                                 Promise._handler(z).fold(function(x, z, to) {
18382                                         to.resolve(f.call(this, z, x));
18383                                 }, x, this, to);
18384                         }, z, promise._handler.receiver, promise._handler);
18385
18386                         return promise;
18387                 };
18388
18389                 return Promise;
18390         };
18391
18392 });
18393 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18394
18395 },{}],217:[function(require,module,exports){
18396 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18397 /** @author Brian Cavalier */
18398 /** @author John Hann */
18399
18400 (function(define) { 'use strict';
18401 define(function(require) {
18402
18403         var inspect = require('../state').inspect;
18404
18405         return function inspection(Promise) {
18406
18407                 Promise.prototype.inspect = function() {
18408                         return inspect(Promise._handler(this));
18409                 };
18410
18411                 return Promise;
18412         };
18413
18414 });
18415 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18416
18417 },{"../state":226}],218:[function(require,module,exports){
18418 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18419 /** @author Brian Cavalier */
18420 /** @author John Hann */
18421
18422 (function(define) { 'use strict';
18423 define(function() {
18424
18425         return function generate(Promise) {
18426
18427                 var resolve = Promise.resolve;
18428
18429                 Promise.iterate = iterate;
18430                 Promise.unfold = unfold;
18431
18432                 return Promise;
18433
18434                 /**
18435                  * @deprecated Use github.com/cujojs/most streams and most.iterate
18436                  * Generate a (potentially infinite) stream of promised values:
18437                  * x, f(x), f(f(x)), etc. until condition(x) returns true
18438                  * @param {function} f function to generate a new x from the previous x
18439                  * @param {function} condition function that, given the current x, returns
18440                  *  truthy when the iterate should stop
18441                  * @param {function} handler function to handle the value produced by f
18442                  * @param {*|Promise} x starting value, may be a promise
18443                  * @return {Promise} the result of the last call to f before
18444                  *  condition returns true
18445                  */
18446                 function iterate(f, condition, handler, x) {
18447                         return unfold(function(x) {
18448                                 return [x, f(x)];
18449                         }, condition, handler, x);
18450                 }
18451
18452                 /**
18453                  * @deprecated Use github.com/cujojs/most streams and most.unfold
18454                  * Generate a (potentially infinite) stream of promised values
18455                  * by applying handler(generator(seed)) iteratively until
18456                  * condition(seed) returns true.
18457                  * @param {function} unspool function that generates a [value, newSeed]
18458                  *  given a seed.
18459                  * @param {function} condition function that, given the current seed, returns
18460                  *  truthy when the unfold should stop
18461                  * @param {function} handler function to handle the value produced by unspool
18462                  * @param x {*|Promise} starting value, may be a promise
18463                  * @return {Promise} the result of the last value produced by unspool before
18464                  *  condition returns true
18465                  */
18466                 function unfold(unspool, condition, handler, x) {
18467                         return resolve(x).then(function(seed) {
18468                                 return resolve(condition(seed)).then(function(done) {
18469                                         return done ? seed : resolve(unspool(seed)).spread(next);
18470                                 });
18471                         });
18472
18473                         function next(item, newSeed) {
18474                                 return resolve(handler(item)).then(function() {
18475                                         return unfold(unspool, condition, handler, newSeed);
18476                                 });
18477                         }
18478                 }
18479         };
18480
18481 });
18482 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18483
18484 },{}],219:[function(require,module,exports){
18485 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18486 /** @author Brian Cavalier */
18487 /** @author John Hann */
18488
18489 (function(define) { 'use strict';
18490 define(function() {
18491
18492         return function progress(Promise) {
18493
18494                 /**
18495                  * @deprecated
18496                  * Register a progress handler for this promise
18497                  * @param {function} onProgress
18498                  * @returns {Promise}
18499                  */
18500                 Promise.prototype.progress = function(onProgress) {
18501                         return this.then(void 0, void 0, onProgress);
18502                 };
18503
18504                 return Promise;
18505         };
18506
18507 });
18508 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18509
18510 },{}],220:[function(require,module,exports){
18511 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18512 /** @author Brian Cavalier */
18513 /** @author John Hann */
18514
18515 (function(define) { 'use strict';
18516 define(function(require) {
18517
18518         var env = require('../env');
18519         var TimeoutError = require('../TimeoutError');
18520
18521         function setTimeout(f, ms, x, y) {
18522                 return env.setTimer(function() {
18523                         f(x, y, ms);
18524                 }, ms);
18525         }
18526
18527         return function timed(Promise) {
18528                 /**
18529                  * Return a new promise whose fulfillment value is revealed only
18530                  * after ms milliseconds
18531                  * @param {number} ms milliseconds
18532                  * @returns {Promise}
18533                  */
18534                 Promise.prototype.delay = function(ms) {
18535                         var p = this._beget();
18536                         this._handler.fold(handleDelay, ms, void 0, p._handler);
18537                         return p;
18538                 };
18539
18540                 function handleDelay(ms, x, h) {
18541                         setTimeout(resolveDelay, ms, x, h);
18542                 }
18543
18544                 function resolveDelay(x, h) {
18545                         h.resolve(x);
18546                 }
18547
18548                 /**
18549                  * Return a new promise that rejects after ms milliseconds unless
18550                  * this promise fulfills earlier, in which case the returned promise
18551                  * fulfills with the same value.
18552                  * @param {number} ms milliseconds
18553                  * @param {Error|*=} reason optional rejection reason to use, defaults
18554                  *   to a TimeoutError if not provided
18555                  * @returns {Promise}
18556                  */
18557                 Promise.prototype.timeout = function(ms, reason) {
18558                         var p = this._beget();
18559                         var h = p._handler;
18560
18561                         var t = setTimeout(onTimeout, ms, reason, p._handler);
18562
18563                         this._handler.visit(h,
18564                                 function onFulfill(x) {
18565                                         env.clearTimer(t);
18566                                         this.resolve(x); // this = h
18567                                 },
18568                                 function onReject(x) {
18569                                         env.clearTimer(t);
18570                                         this.reject(x); // this = h
18571                                 },
18572                                 h.notify);
18573
18574                         return p;
18575                 };
18576
18577                 function onTimeout(reason, h, ms) {
18578                         var e = typeof reason === 'undefined'
18579                                 ? new TimeoutError('timed out after ' + ms + 'ms')
18580                                 : reason;
18581                         h.reject(e);
18582                 }
18583
18584                 return Promise;
18585         };
18586
18587 });
18588 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18589
18590 },{"../TimeoutError":212,"../env":223}],221:[function(require,module,exports){
18591 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18592 /** @author Brian Cavalier */
18593 /** @author John Hann */
18594
18595 (function(define) { 'use strict';
18596 define(function(require) {
18597
18598         var setTimer = require('../env').setTimer;
18599         var format = require('../format');
18600
18601         return function unhandledRejection(Promise) {
18602
18603                 var logError = noop;
18604                 var logInfo = noop;
18605                 var localConsole;
18606
18607                 if(typeof console !== 'undefined') {
18608                         // Alias console to prevent things like uglify's drop_console option from
18609                         // removing console.log/error. Unhandled rejections fall into the same
18610                         // category as uncaught exceptions, and build tools shouldn't silence them.
18611                         localConsole = console;
18612                         logError = typeof localConsole.error !== 'undefined'
18613                                 ? function (e) { localConsole.error(e); }
18614                                 : function (e) { localConsole.log(e); };
18615
18616                         logInfo = typeof localConsole.info !== 'undefined'
18617                                 ? function (e) { localConsole.info(e); }
18618                                 : function (e) { localConsole.log(e); };
18619                 }
18620
18621                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18622                         enqueue(report, rejection);
18623                 };
18624
18625                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
18626                         enqueue(unreport, rejection);
18627                 };
18628
18629                 Promise.onFatalRejection = function(rejection) {
18630                         enqueue(throwit, rejection.value);
18631                 };
18632
18633                 var tasks = [];
18634                 var reported = [];
18635                 var running = null;
18636
18637                 function report(r) {
18638                         if(!r.handled) {
18639                                 reported.push(r);
18640                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
18641                         }
18642                 }
18643
18644                 function unreport(r) {
18645                         var i = reported.indexOf(r);
18646                         if(i >= 0) {
18647                                 reported.splice(i, 1);
18648                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
18649                         }
18650                 }
18651
18652                 function enqueue(f, x) {
18653                         tasks.push(f, x);
18654                         if(running === null) {
18655                                 running = setTimer(flush, 0);
18656                         }
18657                 }
18658
18659                 function flush() {
18660                         running = null;
18661                         while(tasks.length > 0) {
18662                                 tasks.shift()(tasks.shift());
18663                         }
18664                 }
18665
18666                 return Promise;
18667         };
18668
18669         function throwit(e) {
18670                 throw e;
18671         }
18672
18673         function noop() {}
18674
18675 });
18676 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18677
18678 },{"../env":223,"../format":224}],222:[function(require,module,exports){
18679 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18680 /** @author Brian Cavalier */
18681 /** @author John Hann */
18682
18683 (function(define) { 'use strict';
18684 define(function() {
18685
18686         return function addWith(Promise) {
18687                 /**
18688                  * Returns a promise whose handlers will be called with `this` set to
18689                  * the supplied receiver.  Subsequent promises derived from the
18690                  * returned promise will also have their handlers called with receiver
18691                  * as `this`. Calling `with` with undefined or no arguments will return
18692                  * a promise whose handlers will again be called in the usual Promises/A+
18693                  * way (no `this`) thus safely undoing any previous `with` in the
18694                  * promise chain.
18695                  *
18696                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
18697                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
18698                  *
18699                  * @param {object} receiver `this` value for all handlers attached to
18700                  *  the returned promise.
18701                  * @returns {Promise}
18702                  */
18703                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
18704                         var p = this._beget();
18705                         var child = p._handler;
18706                         child.receiver = receiver;
18707                         this._handler.chain(child, receiver);
18708                         return p;
18709                 };
18710
18711                 return Promise;
18712         };
18713
18714 });
18715 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18716
18717
18718 },{}],223:[function(require,module,exports){
18719 (function (process){
18720 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18721 /** @author Brian Cavalier */
18722 /** @author John Hann */
18723
18724 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
18725 (function(define) { 'use strict';
18726 define(function(require) {
18727         /*jshint maxcomplexity:6*/
18728
18729         // Sniff "best" async scheduling option
18730         // Prefer process.nextTick or MutationObserver, then check for
18731         // setTimeout, and finally vertx, since its the only env that doesn't
18732         // have setTimeout
18733
18734         var MutationObs;
18735         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
18736
18737         // Default env
18738         var setTimer = function(f, ms) { return setTimeout(f, ms); };
18739         var clearTimer = function(t) { return clearTimeout(t); };
18740         var asap = function (f) { return capturedSetTimeout(f, 0); };
18741
18742         // Detect specific env
18743         if (isNode()) { // Node
18744                 asap = function (f) { return process.nextTick(f); };
18745
18746         } else if (MutationObs = hasMutationObserver()) { // Modern browser
18747                 asap = initMutationObserver(MutationObs);
18748
18749         } else if (!capturedSetTimeout) { // vert.x
18750                 var vertxRequire = require;
18751                 var vertx = vertxRequire('vertx');
18752                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
18753                 clearTimer = vertx.cancelTimer;
18754                 asap = vertx.runOnLoop || vertx.runOnContext;
18755         }
18756
18757         return {
18758                 setTimer: setTimer,
18759                 clearTimer: clearTimer,
18760                 asap: asap
18761         };
18762
18763         function isNode () {
18764                 return typeof process !== 'undefined' &&
18765                         Object.prototype.toString.call(process) === '[object process]';
18766         }
18767
18768         function hasMutationObserver () {
18769             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
18770                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
18771         }
18772
18773         function initMutationObserver(MutationObserver) {
18774                 var scheduled;
18775                 var node = document.createTextNode('');
18776                 var o = new MutationObserver(run);
18777                 o.observe(node, { characterData: true });
18778
18779                 function run() {
18780                         var f = scheduled;
18781                         scheduled = void 0;
18782                         f();
18783                 }
18784
18785                 var i = 0;
18786                 return function (f) {
18787                         scheduled = f;
18788                         node.data = (i ^= 1);
18789                 };
18790         }
18791 });
18792 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18793
18794 }).call(this,require('_process'))
18795
18796 },{"_process":6}],224:[function(require,module,exports){
18797 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18798 /** @author Brian Cavalier */
18799 /** @author John Hann */
18800
18801 (function(define) { 'use strict';
18802 define(function() {
18803
18804         return {
18805                 formatError: formatError,
18806                 formatObject: formatObject,
18807                 tryStringify: tryStringify
18808         };
18809
18810         /**
18811          * Format an error into a string.  If e is an Error and has a stack property,
18812          * it's returned.  Otherwise, e is formatted using formatObject, with a
18813          * warning added about e not being a proper Error.
18814          * @param {*} e
18815          * @returns {String} formatted string, suitable for output to developers
18816          */
18817         function formatError(e) {
18818                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
18819                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18820         }
18821
18822         /**
18823          * Format an object, detecting "plain" objects and running them through
18824          * JSON.stringify if possible.
18825          * @param {Object} o
18826          * @returns {string}
18827          */
18828         function formatObject(o) {
18829                 var s = String(o);
18830                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18831                         s = tryStringify(o, s);
18832                 }
18833                 return s;
18834         }
18835
18836         /**
18837          * Try to return the result of JSON.stringify(x).  If that fails, return
18838          * defaultValue
18839          * @param {*} x
18840          * @param {*} defaultValue
18841          * @returns {String|*} JSON.stringify(x) or defaultValue
18842          */
18843         function tryStringify(x, defaultValue) {
18844                 try {
18845                         return JSON.stringify(x);
18846                 } catch(e) {
18847                         return defaultValue;
18848                 }
18849         }
18850
18851 });
18852 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18853
18854 },{}],225:[function(require,module,exports){
18855 (function (process){
18856 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18857 /** @author Brian Cavalier */
18858 /** @author John Hann */
18859
18860 (function(define) { 'use strict';
18861 define(function() {
18862
18863         return function makePromise(environment) {
18864
18865                 var tasks = environment.scheduler;
18866                 var emitRejection = initEmitRejection();
18867
18868                 var objectCreate = Object.create ||
18869                         function(proto) {
18870                                 function Child() {}
18871                                 Child.prototype = proto;
18872                                 return new Child();
18873                         };
18874
18875                 /**
18876                  * Create a promise whose fate is determined by resolver
18877                  * @constructor
18878                  * @returns {Promise} promise
18879                  * @name Promise
18880                  */
18881                 function Promise(resolver, handler) {
18882                         this._handler = resolver === Handler ? handler : init(resolver);
18883                 }
18884
18885                 /**
18886                  * Run the supplied resolver
18887                  * @param resolver
18888                  * @returns {Pending}
18889                  */
18890                 function init(resolver) {
18891                         var handler = new Pending();
18892
18893                         try {
18894                                 resolver(promiseResolve, promiseReject, promiseNotify);
18895                         } catch (e) {
18896                                 promiseReject(e);
18897                         }
18898
18899                         return handler;
18900
18901                         /**
18902                          * Transition from pre-resolution state to post-resolution state, notifying
18903                          * all listeners of the ultimate fulfillment or rejection
18904                          * @param {*} x resolution value
18905                          */
18906                         function promiseResolve (x) {
18907                                 handler.resolve(x);
18908                         }
18909                         /**
18910                          * Reject this promise with reason, which will be used verbatim
18911                          * @param {Error|*} reason rejection reason, strongly suggested
18912                          *   to be an Error type
18913                          */
18914                         function promiseReject (reason) {
18915                                 handler.reject(reason);
18916                         }
18917
18918                         /**
18919                          * @deprecated
18920                          * Issue a progress event, notifying all progress listeners
18921                          * @param {*} x progress event payload to pass to all listeners
18922                          */
18923                         function promiseNotify (x) {
18924                                 handler.notify(x);
18925                         }
18926                 }
18927
18928                 // Creation
18929
18930                 Promise.resolve = resolve;
18931                 Promise.reject = reject;
18932                 Promise.never = never;
18933
18934                 Promise._defer = defer;
18935                 Promise._handler = getHandler;
18936
18937                 /**
18938                  * Returns a trusted promise. If x is already a trusted promise, it is
18939                  * returned, otherwise returns a new trusted Promise which follows x.
18940                  * @param  {*} x
18941                  * @return {Promise} promise
18942                  */
18943                 function resolve(x) {
18944                         return isPromise(x) ? x
18945                                 : new Promise(Handler, new Async(getHandler(x)));
18946                 }
18947
18948                 /**
18949                  * Return a reject promise with x as its reason (x is used verbatim)
18950                  * @param {*} x
18951                  * @returns {Promise} rejected promise
18952                  */
18953                 function reject(x) {
18954                         return new Promise(Handler, new Async(new Rejected(x)));
18955                 }
18956
18957                 /**
18958                  * Return a promise that remains pending forever
18959                  * @returns {Promise} forever-pending promise.
18960                  */
18961                 function never() {
18962                         return foreverPendingPromise; // Should be frozen
18963                 }
18964
18965                 /**
18966                  * Creates an internal {promise, resolver} pair
18967                  * @private
18968                  * @returns {Promise}
18969                  */
18970                 function defer() {
18971                         return new Promise(Handler, new Pending());
18972                 }
18973
18974                 // Transformation and flow control
18975
18976                 /**
18977                  * Transform this promise's fulfillment value, returning a new Promise
18978                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
18979                  * is called with the reason.  onProgress *may* be called with updates toward
18980                  * this promise's fulfillment.
18981                  * @param {function=} onFulfilled fulfillment handler
18982                  * @param {function=} onRejected rejection handler
18983                  * @param {function=} onProgress @deprecated progress handler
18984                  * @return {Promise} new promise
18985                  */
18986                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
18987                         var parent = this._handler;
18988                         var state = parent.join().state();
18989
18990                         if ((typeof onFulfilled !== 'function' && state > 0) ||
18991                                 (typeof onRejected !== 'function' && state < 0)) {
18992                                 // Short circuit: value will not change, simply share handler
18993                                 return new this.constructor(Handler, parent);
18994                         }
18995
18996                         var p = this._beget();
18997                         var child = p._handler;
18998
18999                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
19000
19001                         return p;
19002                 };
19003
19004                 /**
19005                  * If this promise cannot be fulfilled due to an error, call onRejected to
19006                  * handle the error. Shortcut for .then(undefined, onRejected)
19007                  * @param {function?} onRejected
19008                  * @return {Promise}
19009                  */
19010                 Promise.prototype['catch'] = function(onRejected) {
19011                         return this.then(void 0, onRejected);
19012                 };
19013
19014                 /**
19015                  * Creates a new, pending promise of the same type as this promise
19016                  * @private
19017                  * @returns {Promise}
19018                  */
19019                 Promise.prototype._beget = function() {
19020                         return begetFrom(this._handler, this.constructor);
19021                 };
19022
19023                 function begetFrom(parent, Promise) {
19024                         var child = new Pending(parent.receiver, parent.join().context);
19025                         return new Promise(Handler, child);
19026                 }
19027
19028                 // Array combinators
19029
19030                 Promise.all = all;
19031                 Promise.race = race;
19032                 Promise._traverse = traverse;
19033
19034                 /**
19035                  * Return a promise that will fulfill when all promises in the
19036                  * input array have fulfilled, or will reject when one of the
19037                  * promises rejects.
19038                  * @param {array} promises array of promises
19039                  * @returns {Promise} promise for array of fulfillment values
19040                  */
19041                 function all(promises) {
19042                         return traverseWith(snd, null, promises);
19043                 }
19044
19045                 /**
19046                  * Array<Promise<X>> -> Promise<Array<f(X)>>
19047                  * @private
19048                  * @param {function} f function to apply to each promise's value
19049                  * @param {Array} promises array of promises
19050                  * @returns {Promise} promise for transformed values
19051                  */
19052                 function traverse(f, promises) {
19053                         return traverseWith(tryCatch2, f, promises);
19054                 }
19055
19056                 function traverseWith(tryMap, f, promises) {
19057                         var handler = typeof f === 'function' ? mapAt : settleAt;
19058
19059                         var resolver = new Pending();
19060                         var pending = promises.length >>> 0;
19061                         var results = new Array(pending);
19062
19063                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
19064                                 x = promises[i];
19065
19066                                 if (x === void 0 && !(i in promises)) {
19067                                         --pending;
19068                                         continue;
19069                                 }
19070
19071                                 traverseAt(promises, handler, i, x, resolver);
19072                         }
19073
19074                         if(pending === 0) {
19075                                 resolver.become(new Fulfilled(results));
19076                         }
19077
19078                         return new Promise(Handler, resolver);
19079
19080                         function mapAt(i, x, resolver) {
19081                                 if(!resolver.resolved) {
19082                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
19083                                 }
19084                         }
19085
19086                         function settleAt(i, x, resolver) {
19087                                 results[i] = x;
19088                                 if(--pending === 0) {
19089                                         resolver.become(new Fulfilled(results));
19090                                 }
19091                         }
19092                 }
19093
19094                 function traverseAt(promises, handler, i, x, resolver) {
19095                         if (maybeThenable(x)) {
19096                                 var h = getHandlerMaybeThenable(x);
19097                                 var s = h.state();
19098
19099                                 if (s === 0) {
19100                                         h.fold(handler, i, void 0, resolver);
19101                                 } else if (s > 0) {
19102                                         handler(i, h.value, resolver);
19103                                 } else {
19104                                         resolver.become(h);
19105                                         visitRemaining(promises, i+1, h);
19106                                 }
19107                         } else {
19108                                 handler(i, x, resolver);
19109                         }
19110                 }
19111
19112                 Promise._visitRemaining = visitRemaining;
19113                 function visitRemaining(promises, start, handler) {
19114                         for(var i=start; i<promises.length; ++i) {
19115                                 markAsHandled(getHandler(promises[i]), handler);
19116                         }
19117                 }
19118
19119                 function markAsHandled(h, handler) {
19120                         if(h === handler) {
19121                                 return;
19122                         }
19123
19124                         var s = h.state();
19125                         if(s === 0) {
19126                                 h.visit(h, void 0, h._unreport);
19127                         } else if(s < 0) {
19128                                 h._unreport();
19129                         }
19130                 }
19131
19132                 /**
19133                  * Fulfill-reject competitive race. Return a promise that will settle
19134                  * to the same state as the earliest input promise to settle.
19135                  *
19136                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
19137                  * must return a promise that is pending forever.  This implementation
19138                  * returns a singleton forever-pending promise, the same singleton that is
19139                  * returned by Promise.never(), thus can be checked with ===
19140                  *
19141                  * @param {array} promises array of promises to race
19142                  * @returns {Promise} if input is non-empty, a promise that will settle
19143                  * to the same outcome as the earliest input promise to settle. if empty
19144                  * is empty, returns a promise that will never settle.
19145                  */
19146                 function race(promises) {
19147                         if(typeof promises !== 'object' || promises === null) {
19148                                 return reject(new TypeError('non-iterable passed to race()'));
19149                         }
19150
19151                         // Sigh, race([]) is untestable unless we return *something*
19152                         // that is recognizable without calling .then() on it.
19153                         return promises.length === 0 ? never()
19154                                  : promises.length === 1 ? resolve(promises[0])
19155                                  : runRace(promises);
19156                 }
19157
19158                 function runRace(promises) {
19159                         var resolver = new Pending();
19160                         var i, x, h;
19161                         for(i=0; i<promises.length; ++i) {
19162                                 x = promises[i];
19163                                 if (x === void 0 && !(i in promises)) {
19164                                         continue;
19165                                 }
19166
19167                                 h = getHandler(x);
19168                                 if(h.state() !== 0) {
19169                                         resolver.become(h);
19170                                         visitRemaining(promises, i+1, h);
19171                                         break;
19172                                 } else {
19173                                         h.visit(resolver, resolver.resolve, resolver.reject);
19174                                 }
19175                         }
19176                         return new Promise(Handler, resolver);
19177                 }
19178
19179                 // Promise internals
19180                 // Below this, everything is @private
19181
19182                 /**
19183                  * Get an appropriate handler for x, without checking for cycles
19184                  * @param {*} x
19185                  * @returns {object} handler
19186                  */
19187                 function getHandler(x) {
19188                         if(isPromise(x)) {
19189                                 return x._handler.join();
19190                         }
19191                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
19192                 }
19193
19194                 /**
19195                  * Get a handler for thenable x.
19196                  * NOTE: You must only call this if maybeThenable(x) == true
19197                  * @param {object|function|Promise} x
19198                  * @returns {object} handler
19199                  */
19200                 function getHandlerMaybeThenable(x) {
19201                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
19202                 }
19203
19204                 /**
19205                  * Get a handler for potentially untrusted thenable x
19206                  * @param {*} x
19207                  * @returns {object} handler
19208                  */
19209                 function getHandlerUntrusted(x) {
19210                         try {
19211                                 var untrustedThen = x.then;
19212                                 return typeof untrustedThen === 'function'
19213                                         ? new Thenable(untrustedThen, x)
19214                                         : new Fulfilled(x);
19215                         } catch(e) {
19216                                 return new Rejected(e);
19217                         }
19218                 }
19219
19220                 /**
19221                  * Handler for a promise that is pending forever
19222                  * @constructor
19223                  */
19224                 function Handler() {}
19225
19226                 Handler.prototype.when
19227                         = Handler.prototype.become
19228                         = Handler.prototype.notify // deprecated
19229                         = Handler.prototype.fail
19230                         = Handler.prototype._unreport
19231                         = Handler.prototype._report
19232                         = noop;
19233
19234                 Handler.prototype._state = 0;
19235
19236                 Handler.prototype.state = function() {
19237                         return this._state;
19238                 };
19239
19240                 /**
19241                  * Recursively collapse handler chain to find the handler
19242                  * nearest to the fully resolved value.
19243                  * @returns {object} handler nearest the fully resolved value
19244                  */
19245                 Handler.prototype.join = function() {
19246                         var h = this;
19247                         while(h.handler !== void 0) {
19248                                 h = h.handler;
19249                         }
19250                         return h;
19251                 };
19252
19253                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
19254                         this.when({
19255                                 resolver: to,
19256                                 receiver: receiver,
19257                                 fulfilled: fulfilled,
19258                                 rejected: rejected,
19259                                 progress: progress
19260                         });
19261                 };
19262
19263                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
19264                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
19265                 };
19266
19267                 Handler.prototype.fold = function(f, z, c, to) {
19268                         this.when(new Fold(f, z, c, to));
19269                 };
19270
19271                 /**
19272                  * Handler that invokes fail() on any handler it becomes
19273                  * @constructor
19274                  */
19275                 function FailIfRejected() {}
19276
19277                 inherit(Handler, FailIfRejected);
19278
19279                 FailIfRejected.prototype.become = function(h) {
19280                         h.fail();
19281                 };
19282
19283                 var failIfRejected = new FailIfRejected();
19284
19285                 /**
19286                  * Handler that manages a queue of consumers waiting on a pending promise
19287                  * @constructor
19288                  */
19289                 function Pending(receiver, inheritedContext) {
19290                         Promise.createContext(this, inheritedContext);
19291
19292                         this.consumers = void 0;
19293                         this.receiver = receiver;
19294                         this.handler = void 0;
19295                         this.resolved = false;
19296                 }
19297
19298                 inherit(Handler, Pending);
19299
19300                 Pending.prototype._state = 0;
19301
19302                 Pending.prototype.resolve = function(x) {
19303                         this.become(getHandler(x));
19304                 };
19305
19306                 Pending.prototype.reject = function(x) {
19307                         if(this.resolved) {
19308                                 return;
19309                         }
19310
19311                         this.become(new Rejected(x));
19312                 };
19313
19314                 Pending.prototype.join = function() {
19315                         if (!this.resolved) {
19316                                 return this;
19317                         }
19318
19319                         var h = this;
19320
19321                         while (h.handler !== void 0) {
19322                                 h = h.handler;
19323                                 if (h === this) {
19324                                         return this.handler = cycle();
19325                                 }
19326                         }
19327
19328                         return h;
19329                 };
19330
19331                 Pending.prototype.run = function() {
19332                         var q = this.consumers;
19333                         var handler = this.handler;
19334                         this.handler = this.handler.join();
19335                         this.consumers = void 0;
19336
19337                         for (var i = 0; i < q.length; ++i) {
19338                                 handler.when(q[i]);
19339                         }
19340                 };
19341
19342                 Pending.prototype.become = function(handler) {
19343                         if(this.resolved) {
19344                                 return;
19345                         }
19346
19347                         this.resolved = true;
19348                         this.handler = handler;
19349                         if(this.consumers !== void 0) {
19350                                 tasks.enqueue(this);
19351                         }
19352
19353                         if(this.context !== void 0) {
19354                                 handler._report(this.context);
19355                         }
19356                 };
19357
19358                 Pending.prototype.when = function(continuation) {
19359                         if(this.resolved) {
19360                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
19361                         } else {
19362                                 if(this.consumers === void 0) {
19363                                         this.consumers = [continuation];
19364                                 } else {
19365                                         this.consumers.push(continuation);
19366                                 }
19367                         }
19368                 };
19369
19370                 /**
19371                  * @deprecated
19372                  */
19373                 Pending.prototype.notify = function(x) {
19374                         if(!this.resolved) {
19375                                 tasks.enqueue(new ProgressTask(x, this));
19376                         }
19377                 };
19378
19379                 Pending.prototype.fail = function(context) {
19380                         var c = typeof context === 'undefined' ? this.context : context;
19381                         this.resolved && this.handler.join().fail(c);
19382                 };
19383
19384                 Pending.prototype._report = function(context) {
19385                         this.resolved && this.handler.join()._report(context);
19386                 };
19387
19388                 Pending.prototype._unreport = function() {
19389                         this.resolved && this.handler.join()._unreport();
19390                 };
19391
19392                 /**
19393                  * Wrap another handler and force it into a future stack
19394                  * @param {object} handler
19395                  * @constructor
19396                  */
19397                 function Async(handler) {
19398                         this.handler = handler;
19399                 }
19400
19401                 inherit(Handler, Async);
19402
19403                 Async.prototype.when = function(continuation) {
19404                         tasks.enqueue(new ContinuationTask(continuation, this));
19405                 };
19406
19407                 Async.prototype._report = function(context) {
19408                         this.join()._report(context);
19409                 };
19410
19411                 Async.prototype._unreport = function() {
19412                         this.join()._unreport();
19413                 };
19414
19415                 /**
19416                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
19417                  * @param {function} then
19418                  * @param {{then: function}} thenable
19419                  * @constructor
19420                  */
19421                 function Thenable(then, thenable) {
19422                         Pending.call(this);
19423                         tasks.enqueue(new AssimilateTask(then, thenable, this));
19424                 }
19425
19426                 inherit(Pending, Thenable);
19427
19428                 /**
19429                  * Handler for a fulfilled promise
19430                  * @param {*} x fulfillment value
19431                  * @constructor
19432                  */
19433                 function Fulfilled(x) {
19434                         Promise.createContext(this);
19435                         this.value = x;
19436                 }
19437
19438                 inherit(Handler, Fulfilled);
19439
19440                 Fulfilled.prototype._state = 1;
19441
19442                 Fulfilled.prototype.fold = function(f, z, c, to) {
19443                         runContinuation3(f, z, this, c, to);
19444                 };
19445
19446                 Fulfilled.prototype.when = function(cont) {
19447                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
19448                 };
19449
19450                 var errorId = 0;
19451
19452                 /**
19453                  * Handler for a rejected promise
19454                  * @param {*} x rejection reason
19455                  * @constructor
19456                  */
19457                 function Rejected(x) {
19458                         Promise.createContext(this);
19459
19460                         this.id = ++errorId;
19461                         this.value = x;
19462                         this.handled = false;
19463                         this.reported = false;
19464
19465                         this._report();
19466                 }
19467
19468                 inherit(Handler, Rejected);
19469
19470                 Rejected.prototype._state = -1;
19471
19472                 Rejected.prototype.fold = function(f, z, c, to) {
19473                         to.become(this);
19474                 };
19475
19476                 Rejected.prototype.when = function(cont) {
19477                         if(typeof cont.rejected === 'function') {
19478                                 this._unreport();
19479                         }
19480                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
19481                 };
19482
19483                 Rejected.prototype._report = function(context) {
19484                         tasks.afterQueue(new ReportTask(this, context));
19485                 };
19486
19487                 Rejected.prototype._unreport = function() {
19488                         if(this.handled) {
19489                                 return;
19490                         }
19491                         this.handled = true;
19492                         tasks.afterQueue(new UnreportTask(this));
19493                 };
19494
19495                 Rejected.prototype.fail = function(context) {
19496                         this.reported = true;
19497                         emitRejection('unhandledRejection', this);
19498                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
19499                 };
19500
19501                 function ReportTask(rejection, context) {
19502                         this.rejection = rejection;
19503                         this.context = context;
19504                 }
19505
19506                 ReportTask.prototype.run = function() {
19507                         if(!this.rejection.handled && !this.rejection.reported) {
19508                                 this.rejection.reported = true;
19509                                 emitRejection('unhandledRejection', this.rejection) ||
19510                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
19511                         }
19512                 };
19513
19514                 function UnreportTask(rejection) {
19515                         this.rejection = rejection;
19516                 }
19517
19518                 UnreportTask.prototype.run = function() {
19519                         if(this.rejection.reported) {
19520                                 emitRejection('rejectionHandled', this.rejection) ||
19521                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
19522                         }
19523                 };
19524
19525                 // Unhandled rejection hooks
19526                 // By default, everything is a noop
19527
19528                 Promise.createContext
19529                         = Promise.enterContext
19530                         = Promise.exitContext
19531                         = Promise.onPotentiallyUnhandledRejection
19532                         = Promise.onPotentiallyUnhandledRejectionHandled
19533                         = Promise.onFatalRejection
19534                         = noop;
19535
19536                 // Errors and singletons
19537
19538                 var foreverPendingHandler = new Handler();
19539                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19540
19541                 function cycle() {
19542                         return new Rejected(new TypeError('Promise cycle'));
19543                 }
19544
19545                 // Task runners
19546
19547                 /**
19548                  * Run a single consumer
19549                  * @constructor
19550                  */
19551                 function ContinuationTask(continuation, handler) {
19552                         this.continuation = continuation;
19553                         this.handler = handler;
19554                 }
19555
19556                 ContinuationTask.prototype.run = function() {
19557                         this.handler.join().when(this.continuation);
19558                 };
19559
19560                 /**
19561                  * Run a queue of progress handlers
19562                  * @constructor
19563                  */
19564                 function ProgressTask(value, handler) {
19565                         this.handler = handler;
19566                         this.value = value;
19567                 }
19568
19569                 ProgressTask.prototype.run = function() {
19570                         var q = this.handler.consumers;
19571                         if(q === void 0) {
19572                                 return;
19573                         }
19574
19575                         for (var c, i = 0; i < q.length; ++i) {
19576                                 c = q[i];
19577                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
19578                         }
19579                 };
19580
19581                 /**
19582                  * Assimilate a thenable, sending it's value to resolver
19583                  * @param {function} then
19584                  * @param {object|function} thenable
19585                  * @param {object} resolver
19586                  * @constructor
19587                  */
19588                 function AssimilateTask(then, thenable, resolver) {
19589                         this._then = then;
19590                         this.thenable = thenable;
19591                         this.resolver = resolver;
19592                 }
19593
19594                 AssimilateTask.prototype.run = function() {
19595                         var h = this.resolver;
19596                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
19597
19598                         function _resolve(x) { h.resolve(x); }
19599                         function _reject(x)  { h.reject(x); }
19600                         function _notify(x)  { h.notify(x); }
19601                 };
19602
19603                 function tryAssimilate(then, thenable, resolve, reject, notify) {
19604                         try {
19605                                 then.call(thenable, resolve, reject, notify);
19606                         } catch (e) {
19607                                 reject(e);
19608                         }
19609                 }
19610
19611                 /**
19612                  * Fold a handler value with z
19613                  * @constructor
19614                  */
19615                 function Fold(f, z, c, to) {
19616                         this.f = f; this.z = z; this.c = c; this.to = to;
19617                         this.resolver = failIfRejected;
19618                         this.receiver = this;
19619                 }
19620
19621                 Fold.prototype.fulfilled = function(x) {
19622                         this.f.call(this.c, this.z, x, this.to);
19623                 };
19624
19625                 Fold.prototype.rejected = function(x) {
19626                         this.to.reject(x);
19627                 };
19628
19629                 Fold.prototype.progress = function(x) {
19630                         this.to.notify(x);
19631                 };
19632
19633                 // Other helpers
19634
19635                 /**
19636                  * @param {*} x
19637                  * @returns {boolean} true iff x is a trusted Promise
19638                  */
19639                 function isPromise(x) {
19640                         return x instanceof Promise;
19641                 }
19642
19643                 /**
19644                  * Test just enough to rule out primitives, in order to take faster
19645                  * paths in some code
19646                  * @param {*} x
19647                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
19648                  */
19649                 function maybeThenable(x) {
19650                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
19651                 }
19652
19653                 function runContinuation1(f, h, receiver, next) {
19654                         if(typeof f !== 'function') {
19655                                 return next.become(h);
19656                         }
19657
19658                         Promise.enterContext(h);
19659                         tryCatchReject(f, h.value, receiver, next);
19660                         Promise.exitContext();
19661                 }
19662
19663                 function runContinuation3(f, x, h, receiver, next) {
19664                         if(typeof f !== 'function') {
19665                                 return next.become(h);
19666                         }
19667
19668                         Promise.enterContext(h);
19669                         tryCatchReject3(f, x, h.value, receiver, next);
19670                         Promise.exitContext();
19671                 }
19672
19673                 /**
19674                  * @deprecated
19675                  */
19676                 function runNotify(f, x, h, receiver, next) {
19677                         if(typeof f !== 'function') {
19678                                 return next.notify(x);
19679                         }
19680
19681                         Promise.enterContext(h);
19682                         tryCatchReturn(f, x, receiver, next);
19683                         Promise.exitContext();
19684                 }
19685
19686                 function tryCatch2(f, a, b) {
19687                         try {
19688                                 return f(a, b);
19689                         } catch(e) {
19690                                 return reject(e);
19691                         }
19692                 }
19693
19694                 /**
19695                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
19696                  * the thrown exception
19697                  */
19698                 function tryCatchReject(f, x, thisArg, next) {
19699                         try {
19700                                 next.become(getHandler(f.call(thisArg, x)));
19701                         } catch(e) {
19702                                 next.become(new Rejected(e));
19703                         }
19704                 }
19705
19706                 /**
19707                  * Same as above, but includes the extra argument parameter.
19708                  */
19709                 function tryCatchReject3(f, x, y, thisArg, next) {
19710                         try {
19711                                 f.call(thisArg, x, y, next);
19712                         } catch(e) {
19713                                 next.become(new Rejected(e));
19714                         }
19715                 }
19716
19717                 /**
19718                  * @deprecated
19719                  * Return f.call(thisArg, x), or if it throws, *return* the exception
19720                  */
19721                 function tryCatchReturn(f, x, thisArg, next) {
19722                         try {
19723                                 next.notify(f.call(thisArg, x));
19724                         } catch(e) {
19725                                 next.notify(e);
19726                         }
19727                 }
19728
19729                 function inherit(Parent, Child) {
19730                         Child.prototype = objectCreate(Parent.prototype);
19731                         Child.prototype.constructor = Child;
19732                 }
19733
19734                 function snd(x, y) {
19735                         return y;
19736                 }
19737
19738                 function noop() {}
19739
19740                 function hasCustomEvent() {
19741                         if(typeof CustomEvent === 'function') {
19742                                 try {
19743                                         var ev = new CustomEvent('unhandledRejection');
19744                                         return ev instanceof CustomEvent;
19745                                 } catch (ignoredException) {}
19746                         }
19747                         return false;
19748                 }
19749
19750                 function hasInternetExplorerCustomEvent() {
19751                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
19752                                 try {
19753                                         // Try to create one event to make sure it's supported
19754                                         var ev = document.createEvent('CustomEvent');
19755                                         ev.initCustomEvent('eventType', false, true, {});
19756                                         return true;
19757                                 } catch (ignoredException) {}
19758                         }
19759                         return false;
19760                 }
19761
19762                 function initEmitRejection() {
19763                         /*global process, self, CustomEvent*/
19764                         if(typeof process !== 'undefined' && process !== null
19765                                 && typeof process.emit === 'function') {
19766                                 // Returning falsy here means to call the default
19767                                 // onPotentiallyUnhandledRejection API.  This is safe even in
19768                                 // browserify since process.emit always returns falsy in browserify:
19769                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
19770                                 return function(type, rejection) {
19771                                         return type === 'unhandledRejection'
19772                                                 ? process.emit(type, rejection.value, rejection)
19773                                                 : process.emit(type, rejection);
19774                                 };
19775                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
19776                                 return (function (self, CustomEvent) {
19777                                         return function (type, rejection) {
19778                                                 var ev = new CustomEvent(type, {
19779                                                         detail: {
19780                                                                 reason: rejection.value,
19781                                                                 key: rejection
19782                                                         },
19783                                                         bubbles: false,
19784                                                         cancelable: true
19785                                                 });
19786
19787                                                 return !self.dispatchEvent(ev);
19788                                         };
19789                                 }(self, CustomEvent));
19790                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
19791                                 return (function(self, document) {
19792                                         return function(type, rejection) {
19793                                                 var ev = document.createEvent('CustomEvent');
19794                                                 ev.initCustomEvent(type, false, true, {
19795                                                         reason: rejection.value,
19796                                                         key: rejection
19797                                                 });
19798
19799                                                 return !self.dispatchEvent(ev);
19800                                         };
19801                                 }(self, document));
19802                         }
19803
19804                         return noop;
19805                 }
19806
19807                 return Promise;
19808         };
19809 });
19810 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19811
19812 }).call(this,require('_process'))
19813
19814 },{"_process":6}],226:[function(require,module,exports){
19815 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19816 /** @author Brian Cavalier */
19817 /** @author John Hann */
19818
19819 (function(define) { 'use strict';
19820 define(function() {
19821
19822         return {
19823                 pending: toPendingState,
19824                 fulfilled: toFulfilledState,
19825                 rejected: toRejectedState,
19826                 inspect: inspect
19827         };
19828
19829         function toPendingState() {
19830                 return { state: 'pending' };
19831         }
19832
19833         function toRejectedState(e) {
19834                 return { state: 'rejected', reason: e };
19835         }
19836
19837         function toFulfilledState(x) {
19838                 return { state: 'fulfilled', value: x };
19839         }
19840
19841         function inspect(handler) {
19842                 var state = handler.state();
19843                 return state === 0 ? toPendingState()
19844                          : state > 0   ? toFulfilledState(handler.value)
19845                                        : toRejectedState(handler.value);
19846         }
19847
19848 });
19849 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19850
19851 },{}],227:[function(require,module,exports){
19852 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19853
19854 /**
19855  * Promises/A+ and when() implementation
19856  * when is part of the cujoJS family of libraries (http://cujojs.com/)
19857  * @author Brian Cavalier
19858  * @author John Hann
19859  */
19860 (function(define) { 'use strict';
19861 define(function (require) {
19862
19863         var timed = require('./lib/decorators/timed');
19864         var array = require('./lib/decorators/array');
19865         var flow = require('./lib/decorators/flow');
19866         var fold = require('./lib/decorators/fold');
19867         var inspect = require('./lib/decorators/inspect');
19868         var generate = require('./lib/decorators/iterate');
19869         var progress = require('./lib/decorators/progress');
19870         var withThis = require('./lib/decorators/with');
19871         var unhandledRejection = require('./lib/decorators/unhandledRejection');
19872         var TimeoutError = require('./lib/TimeoutError');
19873
19874         var Promise = [array, flow, fold, generate, progress,
19875                 inspect, withThis, timed, unhandledRejection]
19876                 .reduce(function(Promise, feature) {
19877                         return feature(Promise);
19878                 }, require('./lib/Promise'));
19879
19880         var apply = require('./lib/apply')(Promise);
19881
19882         // Public API
19883
19884         when.promise     = promise;              // Create a pending promise
19885         when.resolve     = Promise.resolve;      // Create a resolved promise
19886         when.reject      = Promise.reject;       // Create a rejected promise
19887
19888         when.lift        = lift;                 // lift a function to return promises
19889         when['try']      = attempt;              // call a function and return a promise
19890         when.attempt     = attempt;              // alias for when.try
19891
19892         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19893         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19894
19895         when.join        = join;                 // Join 2 or more promises
19896
19897         when.all         = all;                  // Resolve a list of promises
19898         when.settle      = settle;               // Settle a list of promises
19899
19900         when.any         = lift(Promise.any);    // One-winner race
19901         when.some        = lift(Promise.some);   // Multi-winner race
19902         when.race        = lift(Promise.race);   // First-to-settle race
19903
19904         when.map         = map;                  // Array.map() for promises
19905         when.filter      = filter;               // Array.filter() for promises
19906         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
19907         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
19908
19909         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
19910
19911         when.Promise     = Promise;              // Promise constructor
19912         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
19913
19914         // Error types
19915
19916         when.TimeoutError = TimeoutError;
19917
19918         /**
19919          * Get a trusted promise for x, or by transforming x with onFulfilled
19920          *
19921          * @param {*} x
19922          * @param {function?} onFulfilled callback to be called when x is
19923          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
19924          *   will be invoked immediately.
19925          * @param {function?} onRejected callback to be called when x is
19926          *   rejected.
19927          * @param {function?} onProgress callback to be called when progress updates
19928          *   are issued for x. @deprecated
19929          * @returns {Promise} a new promise that will fulfill with the return
19930          *   value of callback or errback or the completion value of promiseOrValue if
19931          *   callback and/or errback is not supplied.
19932          */
19933         function when(x, onFulfilled, onRejected, onProgress) {
19934                 var p = Promise.resolve(x);
19935                 if (arguments.length < 2) {
19936                         return p;
19937                 }
19938
19939                 return p.then(onFulfilled, onRejected, onProgress);
19940         }
19941
19942         /**
19943          * Creates a new promise whose fate is determined by resolver.
19944          * @param {function} resolver function(resolve, reject, notify)
19945          * @returns {Promise} promise whose fate is determine by resolver
19946          */
19947         function promise(resolver) {
19948                 return new Promise(resolver);
19949         }
19950
19951         /**
19952          * Lift the supplied function, creating a version of f that returns
19953          * promises, and accepts promises as arguments.
19954          * @param {function} f
19955          * @returns {Function} version of f that returns promises
19956          */
19957         function lift(f) {
19958                 return function() {
19959                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
19960                                 a[i] = arguments[i];
19961                         }
19962                         return apply(f, this, a);
19963                 };
19964         }
19965
19966         /**
19967          * Call f in a future turn, with the supplied args, and return a promise
19968          * for the result.
19969          * @param {function} f
19970          * @returns {Promise}
19971          */
19972         function attempt(f /*, args... */) {
19973                 /*jshint validthis:true */
19974                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
19975                         a[i] = arguments[i+1];
19976                 }
19977                 return apply(f, this, a);
19978         }
19979
19980         /**
19981          * Creates a {promise, resolver} pair, either or both of which
19982          * may be given out safely to consumers.
19983          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19984          */
19985         function defer() {
19986                 return new Deferred();
19987         }
19988
19989         function Deferred() {
19990                 var p = Promise._defer();
19991
19992                 function resolve(x) { p._handler.resolve(x); }
19993                 function reject(x) { p._handler.reject(x); }
19994                 function notify(x) { p._handler.notify(x); }
19995
19996                 this.promise = p;
19997                 this.resolve = resolve;
19998                 this.reject = reject;
19999                 this.notify = notify;
20000                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
20001         }
20002
20003         /**
20004          * Determines if x is promise-like, i.e. a thenable object
20005          * NOTE: Will return true for *any thenable object*, and isn't truly
20006          * safe, since it may attempt to access the `then` property of x (i.e.
20007          *  clever/malicious getters may do weird things)
20008          * @param {*} x anything
20009          * @returns {boolean} true if x is promise-like
20010          */
20011         function isPromiseLike(x) {
20012                 return x && typeof x.then === 'function';
20013         }
20014
20015         /**
20016          * Return a promise that will resolve only once all the supplied arguments
20017          * have resolved. The resolution value of the returned promise will be an array
20018          * containing the resolution values of each of the arguments.
20019          * @param {...*} arguments may be a mix of promises and values
20020          * @returns {Promise}
20021          */
20022         function join(/* ...promises */) {
20023                 return Promise.all(arguments);
20024         }
20025
20026         /**
20027          * Return a promise that will fulfill once all input promises have
20028          * fulfilled, or reject when any one input promise rejects.
20029          * @param {array|Promise} promises array (or promise for an array) of promises
20030          * @returns {Promise}
20031          */
20032         function all(promises) {
20033                 return when(promises, Promise.all);
20034         }
20035
20036         /**
20037          * Return a promise that will always fulfill with an array containing
20038          * the outcome states of all input promises.  The returned promise
20039          * will only reject if `promises` itself is a rejected promise.
20040          * @param {array|Promise} promises array (or promise for an array) of promises
20041          * @returns {Promise} promise for array of settled state descriptors
20042          */
20043         function settle(promises) {
20044                 return when(promises, Promise.settle);
20045         }
20046
20047         /**
20048          * Promise-aware array map function, similar to `Array.prototype.map()`,
20049          * but input array may contain promises or values.
20050          * @param {Array|Promise} promises array of anything, may contain promises and values
20051          * @param {function(x:*, index:Number):*} mapFunc map function which may
20052          *  return a promise or value
20053          * @returns {Promise} promise that will fulfill with an array of mapped values
20054          *  or reject if any input promise rejects.
20055          */
20056         function map(promises, mapFunc) {
20057                 return when(promises, function(promises) {
20058                         return Promise.map(promises, mapFunc);
20059                 });
20060         }
20061
20062         /**
20063          * Filter the provided array of promises using the provided predicate.  Input may
20064          * contain promises and values
20065          * @param {Array|Promise} promises array of promises and values
20066          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20067          *  Must return truthy (or promise for truthy) for items to retain.
20068          * @returns {Promise} promise that will fulfill with an array containing all items
20069          *  for which predicate returned truthy.
20070          */
20071         function filter(promises, predicate) {
20072                 return when(promises, function(promises) {
20073                         return Promise.filter(promises, predicate);
20074                 });
20075         }
20076
20077         return when;
20078 });
20079 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
20080
20081 },{"./lib/Promise":210,"./lib/TimeoutError":212,"./lib/apply":213,"./lib/decorators/array":214,"./lib/decorators/flow":215,"./lib/decorators/fold":216,"./lib/decorators/inspect":217,"./lib/decorators/iterate":218,"./lib/decorators/progress":219,"./lib/decorators/timed":220,"./lib/decorators/unhandledRejection":221,"./lib/decorators/with":222}],228:[function(require,module,exports){
20082 var nativeIsArray = Array.isArray
20083 var toString = Object.prototype.toString
20084
20085 module.exports = nativeIsArray || isArray
20086
20087 function isArray(obj) {
20088     return toString.call(obj) === "[object Array]"
20089 }
20090
20091 },{}],229:[function(require,module,exports){
20092 "use strict";
20093 Object.defineProperty(exports, "__esModule", { value: true });
20094 var APIv3_1 = require("./api/APIv3");
20095 exports.APIv3 = APIv3_1.APIv3;
20096 var ModelCreator_1 = require("./api/ModelCreator");
20097 exports.ModelCreator = ModelCreator_1.ModelCreator;
20098
20099 },{"./api/APIv3":242,"./api/ModelCreator":243}],230:[function(require,module,exports){
20100 "use strict";
20101 function __export(m) {
20102     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20103 }
20104 Object.defineProperty(exports, "__esModule", { value: true });
20105 var Component_1 = require("./component/Component");
20106 exports.Component = Component_1.Component;
20107 var ComponentService_1 = require("./component/ComponentService");
20108 exports.ComponentService = ComponentService_1.ComponentService;
20109 var HandlerBase_1 = require("./component/utils/HandlerBase");
20110 exports.HandlerBase = HandlerBase_1.HandlerBase;
20111 var AttributionComponent_1 = require("./component/AttributionComponent");
20112 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
20113 var BackgroundComponent_1 = require("./component/BackgroundComponent");
20114 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
20115 var BearingComponent_1 = require("./component/BearingComponent");
20116 exports.BearingComponent = BearingComponent_1.BearingComponent;
20117 var CacheComponent_1 = require("./component/CacheComponent");
20118 exports.CacheComponent = CacheComponent_1.CacheComponent;
20119 var CoverComponent_1 = require("./component/CoverComponent");
20120 exports.CoverComponent = CoverComponent_1.CoverComponent;
20121 var DebugComponent_1 = require("./component/DebugComponent");
20122 exports.DebugComponent = DebugComponent_1.DebugComponent;
20123 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
20124 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
20125 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
20126 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
20127 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
20128 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
20129 var ImageComponent_1 = require("./component/ImageComponent");
20130 exports.ImageComponent = ImageComponent_1.ImageComponent;
20131 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
20132 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
20133 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
20134 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
20135 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
20136 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
20137 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
20138 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
20139 var LoadingComponent_1 = require("./component/LoadingComponent");
20140 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
20141 var Marker_1 = require("./component/marker/marker/Marker");
20142 exports.Marker = Marker_1.Marker;
20143 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
20144 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
20145 var MarkerScene_1 = require("./component/marker/MarkerScene");
20146 exports.MarkerScene = MarkerScene_1.MarkerScene;
20147 var MarkerSet_1 = require("./component/marker/MarkerSet");
20148 exports.MarkerSet = MarkerSet_1.MarkerSet;
20149 var MouseComponent_1 = require("./component/mouse/MouseComponent");
20150 exports.MouseComponent = MouseComponent_1.MouseComponent;
20151 var BounceHandler_1 = require("./component/mouse/BounceHandler");
20152 exports.BounceHandler = BounceHandler_1.BounceHandler;
20153 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
20154 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
20155 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
20156 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
20157 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
20158 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
20159 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
20160 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
20161 var Popup_1 = require("./component/popup/popup/Popup");
20162 exports.Popup = Popup_1.Popup;
20163 var PopupComponent_1 = require("./component/popup/PopupComponent");
20164 exports.PopupComponent = PopupComponent_1.PopupComponent;
20165 var NavigationComponent_1 = require("./component/NavigationComponent");
20166 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
20167 var RouteComponent_1 = require("./component/RouteComponent");
20168 exports.RouteComponent = RouteComponent_1.RouteComponent;
20169 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
20170 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
20171 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
20172 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
20173 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
20174 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
20175 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
20176 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
20177 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
20178 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
20179 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
20180 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
20181 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
20182 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
20183 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
20184 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
20185 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
20186 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
20187 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
20188 exports.CircleMarker = CircleMarker_1.CircleMarker;
20189 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
20190 exports.SliderComponent = SliderComponent_1.SliderComponent;
20191 var StatsComponent_1 = require("./component/StatsComponent");
20192 exports.StatsComponent = StatsComponent_1.StatsComponent;
20193 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
20194 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
20195 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
20196 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
20197 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
20198 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
20199 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
20200 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
20201 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
20202 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
20203 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
20204 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
20205 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
20206 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
20207 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
20208 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
20209 var Tag_1 = require("./component/tag/tag/Tag");
20210 exports.Tag = Tag_1.Tag;
20211 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
20212 exports.OutlineTag = OutlineTag_1.OutlineTag;
20213 var RenderTag_1 = require("./component/tag/tag/RenderTag");
20214 exports.RenderTag = RenderTag_1.RenderTag;
20215 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
20216 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
20217 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
20218 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
20219 var SpotTag_1 = require("./component/tag/tag/SpotTag");
20220 exports.SpotTag = SpotTag_1.SpotTag;
20221 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
20222 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
20223 var TagComponent_1 = require("./component/tag/TagComponent");
20224 exports.TagComponent = TagComponent_1.TagComponent;
20225 var TagCreator_1 = require("./component/tag/TagCreator");
20226 exports.TagCreator = TagCreator_1.TagCreator;
20227 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
20228 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
20229 var TagMode_1 = require("./component/tag/TagMode");
20230 exports.TagMode = TagMode_1.TagMode;
20231 var TagOperation_1 = require("./component/tag/TagOperation");
20232 exports.TagOperation = TagOperation_1.TagOperation;
20233 var TagScene_1 = require("./component/tag/TagScene");
20234 exports.TagScene = TagScene_1.TagScene;
20235 var TagSet_1 = require("./component/tag/TagSet");
20236 exports.TagSet = TagSet_1.TagSet;
20237 var Geometry_1 = require("./component/tag/geometry/Geometry");
20238 exports.Geometry = Geometry_1.Geometry;
20239 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
20240 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
20241 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
20242 exports.RectGeometry = RectGeometry_1.RectGeometry;
20243 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
20244 exports.PointGeometry = PointGeometry_1.PointGeometry;
20245 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
20246 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
20247 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
20248 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
20249 __export(require("./component/interfaces/interfaces"));
20250
20251 },{"./component/AttributionComponent":244,"./component/BackgroundComponent":245,"./component/BearingComponent":246,"./component/CacheComponent":247,"./component/Component":248,"./component/ComponentService":249,"./component/CoverComponent":250,"./component/DebugComponent":251,"./component/ImageComponent":252,"./component/LoadingComponent":253,"./component/NavigationComponent":254,"./component/RouteComponent":255,"./component/StatsComponent":256,"./component/direction/DirectionComponent":257,"./component/direction/DirectionDOMCalculator":258,"./component/direction/DirectionDOMRenderer":259,"./component/imageplane/ImagePlaneComponent":260,"./component/imageplane/ImagePlaneFactory":261,"./component/imageplane/ImagePlaneGLRenderer":262,"./component/imageplane/ImagePlaneScene":263,"./component/imageplane/ImagePlaneShaders":264,"./component/imageplane/SliderComponent":265,"./component/interfaces/interfaces":267,"./component/keyboard/KeySequenceNavigationHandler":268,"./component/keyboard/KeySpatialNavigationHandler":269,"./component/keyboard/KeyZoomHandler":270,"./component/keyboard/KeyboardComponent":271,"./component/marker/MarkerComponent":273,"./component/marker/MarkerScene":274,"./component/marker/MarkerSet":275,"./component/marker/marker/CircleMarker":276,"./component/marker/marker/Marker":277,"./component/marker/marker/SimpleMarker":278,"./component/mouse/BounceHandler":279,"./component/mouse/DoubleClickZoomHandler":280,"./component/mouse/DragPanHandler":281,"./component/mouse/MouseComponent":282,"./component/mouse/ScrollZoomHandler":283,"./component/mouse/TouchZoomHandler":284,"./component/popup/PopupComponent":286,"./component/popup/popup/Popup":287,"./component/sequence/SequenceComponent":288,"./component/sequence/SequenceDOMInteraction":289,"./component/sequence/SequenceDOMRenderer":290,"./component/tag/TagComponent":292,"./component/tag/TagCreator":293,"./component/tag/TagDOMRenderer":294,"./component/tag/TagMode":295,"./component/tag/TagOperation":296,"./component/tag/TagScene":297,"./component/tag/TagSet":298,"./component/tag/error/GeometryTagError":299,"./component/tag/geometry/Geometry":300,"./component/tag/geometry/PointGeometry":301,"./component/tag/geometry/PolygonGeometry":302,"./component/tag/geometry/RectGeometry":303,"./component/tag/geometry/VertexGeometry":304,"./component/tag/handlers/CreateHandlerBase":305,"./component/tag/handlers/CreatePointHandler":306,"./component/tag/handlers/CreatePolygonHandler":307,"./component/tag/handlers/CreateRectDragHandler":308,"./component/tag/handlers/CreateRectHandler":309,"./component/tag/handlers/CreateVertexHandler":310,"./component/tag/handlers/EditVertexHandler":311,"./component/tag/handlers/TagHandlerBase":312,"./component/tag/tag/OutlineCreateTag":313,"./component/tag/tag/OutlineRenderTag":314,"./component/tag/tag/OutlineTag":315,"./component/tag/tag/RenderTag":316,"./component/tag/tag/SpotRenderTag":317,"./component/tag/tag/SpotTag":318,"./component/tag/tag/Tag":319,"./component/utils/HandlerBase":320}],231:[function(require,module,exports){
20252 "use strict";
20253 Object.defineProperty(exports, "__esModule", { value: true });
20254 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
20255 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
20256 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
20257 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
20258 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
20259 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
20260 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
20261 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
20262 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
20263 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
20264
20265 },{"./graph/edge/EdgeCalculator":338,"./graph/edge/EdgeCalculatorCoefficients":339,"./graph/edge/EdgeCalculatorDirections":340,"./graph/edge/EdgeCalculatorSettings":341,"./graph/edge/EdgeDirection":342}],232:[function(require,module,exports){
20266 "use strict";
20267 Object.defineProperty(exports, "__esModule", { value: true });
20268 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
20269 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
20270 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
20271 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
20272 var MapillaryError_1 = require("./error/MapillaryError");
20273 exports.MapillaryError = MapillaryError_1.MapillaryError;
20274
20275 },{"./error/ArgumentMapillaryError":321,"./error/GraphMapillaryError":322,"./error/MapillaryError":323}],233:[function(require,module,exports){
20276 "use strict";
20277 Object.defineProperty(exports, "__esModule", { value: true });
20278 var Camera_1 = require("./geo/Camera");
20279 exports.Camera = Camera_1.Camera;
20280 var GeoCoords_1 = require("./geo/GeoCoords");
20281 exports.GeoCoords = GeoCoords_1.GeoCoords;
20282 var ViewportCoords_1 = require("./geo/ViewportCoords");
20283 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
20284 var Spatial_1 = require("./geo/Spatial");
20285 exports.Spatial = Spatial_1.Spatial;
20286 var Transform_1 = require("./geo/Transform");
20287 exports.Transform = Transform_1.Transform;
20288
20289 },{"./geo/Camera":324,"./geo/GeoCoords":325,"./geo/Spatial":326,"./geo/Transform":327,"./geo/ViewportCoords":328}],234:[function(require,module,exports){
20290 "use strict";
20291 Object.defineProperty(exports, "__esModule", { value: true });
20292 var FilterCreator_1 = require("./graph/FilterCreator");
20293 exports.FilterCreator = FilterCreator_1.FilterCreator;
20294 var Graph_1 = require("./graph/Graph");
20295 exports.Graph = Graph_1.Graph;
20296 var GraphCalculator_1 = require("./graph/GraphCalculator");
20297 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
20298 var GraphService_1 = require("./graph/GraphService");
20299 exports.GraphService = GraphService_1.GraphService;
20300 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
20301 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
20302 var MeshReader_1 = require("./graph/MeshReader");
20303 exports.MeshReader = MeshReader_1.MeshReader;
20304 var Node_1 = require("./graph/Node");
20305 exports.Node = Node_1.Node;
20306 var NodeCache_1 = require("./graph/NodeCache");
20307 exports.NodeCache = NodeCache_1.NodeCache;
20308 var Sequence_1 = require("./graph/Sequence");
20309 exports.Sequence = Sequence_1.Sequence;
20310
20311 },{"./graph/FilterCreator":329,"./graph/Graph":330,"./graph/GraphCalculator":331,"./graph/GraphService":332,"./graph/ImageLoadingService":333,"./graph/MeshReader":334,"./graph/Node":335,"./graph/NodeCache":336,"./graph/Sequence":337}],235:[function(require,module,exports){
20312 "use strict";
20313 /**
20314  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
20315  * @name Mapillary
20316  */
20317 function __export(m) {
20318     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20319 }
20320 Object.defineProperty(exports, "__esModule", { value: true });
20321 __export(require("./Support"));
20322 var Edge_1 = require("./Edge");
20323 exports.EdgeDirection = Edge_1.EdgeDirection;
20324 var Render_1 = require("./Render");
20325 exports.RenderMode = Render_1.RenderMode;
20326 var Viewer_1 = require("./Viewer");
20327 exports.Alignment = Viewer_1.Alignment;
20328 exports.ImageSize = Viewer_1.ImageSize;
20329 exports.Viewer = Viewer_1.Viewer;
20330 var TagComponent = require("./component/tag/Tag");
20331 exports.TagComponent = TagComponent;
20332 var MarkerComponent = require("./component/marker/Marker");
20333 exports.MarkerComponent = MarkerComponent;
20334 var PopupComponent = require("./component/popup/Popup");
20335 exports.PopupComponent = PopupComponent;
20336
20337 },{"./Edge":231,"./Render":236,"./Support":238,"./Viewer":241,"./component/marker/Marker":272,"./component/popup/Popup":285,"./component/tag/Tag":291}],236:[function(require,module,exports){
20338 "use strict";
20339 Object.defineProperty(exports, "__esModule", { value: true });
20340 var DOMRenderer_1 = require("./render/DOMRenderer");
20341 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
20342 var GLRenderer_1 = require("./render/GLRenderer");
20343 exports.GLRenderer = GLRenderer_1.GLRenderer;
20344 var GLRenderStage_1 = require("./render/GLRenderStage");
20345 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
20346 var RenderCamera_1 = require("./render/RenderCamera");
20347 exports.RenderCamera = RenderCamera_1.RenderCamera;
20348 var RenderMode_1 = require("./render/RenderMode");
20349 exports.RenderMode = RenderMode_1.RenderMode;
20350 var RenderService_1 = require("./render/RenderService");
20351 exports.RenderService = RenderService_1.RenderService;
20352
20353 },{"./render/DOMRenderer":343,"./render/GLRenderStage":344,"./render/GLRenderer":345,"./render/RenderCamera":346,"./render/RenderMode":347,"./render/RenderService":348}],237:[function(require,module,exports){
20354 "use strict";
20355 Object.defineProperty(exports, "__esModule", { value: true });
20356 var State_1 = require("./state/State");
20357 exports.State = State_1.State;
20358 var StateBase_1 = require("./state/states/StateBase");
20359 exports.StateBase = StateBase_1.StateBase;
20360 var StateContext_1 = require("./state/StateContext");
20361 exports.StateContext = StateContext_1.StateContext;
20362 var StateService_1 = require("./state/StateService");
20363 exports.StateService = StateService_1.StateService;
20364 var TraversingState_1 = require("./state/states/TraversingState");
20365 exports.TraversingState = TraversingState_1.TraversingState;
20366 var WaitingState_1 = require("./state/states/WaitingState");
20367 exports.WaitingState = WaitingState_1.WaitingState;
20368
20369 },{"./state/State":349,"./state/StateContext":350,"./state/StateService":351,"./state/states/StateBase":352,"./state/states/TraversingState":353,"./state/states/WaitingState":354}],238:[function(require,module,exports){
20370 "use strict";
20371 Object.defineProperty(exports, "__esModule", { value: true });
20372 var support = require("./utils/Support");
20373 /**
20374  * Test whether the current browser supports the full
20375  * functionality of MapillaryJS.
20376  *
20377  * @description The full functionality includes WebGL rendering.
20378  *
20379  * @return {boolean}
20380  *
20381  * @example `var supported = Mapillary.isSupported();`
20382  */
20383 function isSupported() {
20384     return isFallbackSupported() &&
20385         support.isWebGLSupportedCached();
20386 }
20387 exports.isSupported = isSupported;
20388 /**
20389  * Test whether the current browser supports the fallback
20390  * functionality of MapillaryJS.
20391  *
20392  * @description The fallback functionality does not include WebGL
20393  * rendering, only 2D canvas rendering.
20394  *
20395  * @return {boolean}
20396  *
20397  * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
20398  */
20399 function isFallbackSupported() {
20400     return support.isBrowser() &&
20401         support.isArraySupported() &&
20402         support.isFunctionSupported() &&
20403         support.isJSONSupported() &&
20404         support.isObjectSupported();
20405 }
20406 exports.isFallbackSupported = isFallbackSupported;
20407
20408 },{"./utils/Support":362}],239:[function(require,module,exports){
20409 "use strict";
20410 Object.defineProperty(exports, "__esModule", { value: true });
20411 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
20412 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
20413 var ImageTileStore_1 = require("./tiles/ImageTileStore");
20414 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
20415 var TextureProvider_1 = require("./tiles/TextureProvider");
20416 exports.TextureProvider = TextureProvider_1.TextureProvider;
20417 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
20418 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
20419
20420 },{"./tiles/ImageTileLoader":355,"./tiles/ImageTileStore":356,"./tiles/RegionOfInterestCalculator":357,"./tiles/TextureProvider":358}],240:[function(require,module,exports){
20421 "use strict";
20422 function __export(m) {
20423     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20424 }
20425 Object.defineProperty(exports, "__esModule", { value: true });
20426 var DOM_1 = require("./utils/DOM");
20427 exports.DOM = DOM_1.DOM;
20428 var EventEmitter_1 = require("./utils/EventEmitter");
20429 exports.EventEmitter = EventEmitter_1.EventEmitter;
20430 var Settings_1 = require("./utils/Settings");
20431 exports.Settings = Settings_1.Settings;
20432 __export(require("./utils/Support"));
20433 var Urls_1 = require("./utils/Urls");
20434 exports.Urls = Urls_1.Urls;
20435
20436 },{"./utils/DOM":359,"./utils/EventEmitter":360,"./utils/Settings":361,"./utils/Support":362,"./utils/Urls":363}],241:[function(require,module,exports){
20437 "use strict";
20438 Object.defineProperty(exports, "__esModule", { value: true });
20439 var Alignment_1 = require("./viewer/Alignment");
20440 exports.Alignment = Alignment_1.Alignment;
20441 var CacheService_1 = require("./viewer/CacheService");
20442 exports.CacheService = CacheService_1.CacheService;
20443 var ComponentController_1 = require("./viewer/ComponentController");
20444 exports.ComponentController = ComponentController_1.ComponentController;
20445 var Container_1 = require("./viewer/Container");
20446 exports.Container = Container_1.Container;
20447 var Observer_1 = require("./viewer/Observer");
20448 exports.Observer = Observer_1.Observer;
20449 var ImageSize_1 = require("./viewer/ImageSize");
20450 exports.ImageSize = ImageSize_1.ImageSize;
20451 var KeyboardService_1 = require("./viewer/KeyboardService");
20452 exports.KeyboardService = KeyboardService_1.KeyboardService;
20453 var LoadingService_1 = require("./viewer/LoadingService");
20454 exports.LoadingService = LoadingService_1.LoadingService;
20455 var MouseService_1 = require("./viewer/MouseService");
20456 exports.MouseService = MouseService_1.MouseService;
20457 var Navigator_1 = require("./viewer/Navigator");
20458 exports.Navigator = Navigator_1.Navigator;
20459 var Projection_1 = require("./viewer/Projection");
20460 exports.Projection = Projection_1.Projection;
20461 var SpriteService_1 = require("./viewer/SpriteService");
20462 exports.SpriteService = SpriteService_1.SpriteService;
20463 var TouchService_1 = require("./viewer/TouchService");
20464 exports.TouchService = TouchService_1.TouchService;
20465 var Viewer_1 = require("./viewer/Viewer");
20466 exports.Viewer = Viewer_1.Viewer;
20467
20468 },{"./viewer/Alignment":364,"./viewer/CacheService":365,"./viewer/ComponentController":366,"./viewer/Container":367,"./viewer/ImageSize":368,"./viewer/KeyboardService":369,"./viewer/LoadingService":370,"./viewer/MouseService":371,"./viewer/Navigator":372,"./viewer/Observer":373,"./viewer/Projection":374,"./viewer/SpriteService":375,"./viewer/TouchService":376,"./viewer/Viewer":377}],242:[function(require,module,exports){
20469 "use strict";
20470 /// <reference path="../../typings/index.d.ts" />
20471 Object.defineProperty(exports, "__esModule", { value: true });
20472 var Observable_1 = require("rxjs/Observable");
20473 require("rxjs/add/observable/defer");
20474 require("rxjs/add/observable/fromPromise");
20475 require("rxjs/add/operator/catch");
20476 require("rxjs/add/operator/map");
20477 var API_1 = require("../API");
20478 /**
20479  * @class APIv3
20480  *
20481  * @classdesc Provides methods for access of API v3.
20482  */
20483 var APIv3 = (function () {
20484     /**
20485      * Create a new api v3 instance.
20486      *
20487      * @param {number} clientId - Client id for API requests.
20488      * @param {number} [token] - Optional bearer token for API requests of
20489      * protected resources.
20490      * @param {ModelCreator} [creator] - Optional model creator instance.
20491      */
20492     function APIv3(clientId, token, creator) {
20493         this._clientId = clientId;
20494         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
20495         this._model = this._modelCreator.createModel(clientId, token);
20496         this._pageCount = 999;
20497         this._pathImageByKey = "imageByKey";
20498         this._pathImageCloseTo = "imageCloseTo";
20499         this._pathImagesByH = "imagesByH";
20500         this._pathImageViewAdd = "imageViewAdd";
20501         this._pathSequenceByKey = "sequenceByKey";
20502         this._pathSequenceViewAdd = "sequenceViewAdd";
20503         this._propertiesCore = [
20504             "cl",
20505             "l",
20506             "sequence",
20507         ];
20508         this._propertiesFill = [
20509             "captured_at",
20510             "user",
20511             "project",
20512         ];
20513         this._propertiesKey = [
20514             "key",
20515         ];
20516         this._propertiesSequence = [
20517             "keys",
20518         ];
20519         this._propertiesSpatial = [
20520             "atomic_scale",
20521             "ca",
20522             "calt",
20523             "cca",
20524             "cfocal",
20525             "gpano",
20526             "height",
20527             "merge_cc",
20528             "merge_version",
20529             "c_rotation",
20530             "orientation",
20531             "width",
20532         ];
20533         this._propertiesUser = [
20534             "username",
20535         ];
20536     }
20537     APIv3.prototype.imageByKeyFill$ = function (keys) {
20538         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20539             this._pathImageByKey,
20540             keys,
20541             this._propertiesKey
20542                 .concat(this._propertiesFill)
20543                 .concat(this._propertiesSpatial),
20544             this._propertiesKey
20545                 .concat(this._propertiesUser)
20546         ]))
20547             .map(function (value) {
20548             if (!value) {
20549                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20550             }
20551             return value.json.imageByKey;
20552         }), this._pathImageByKey, keys);
20553     };
20554     APIv3.prototype.imageByKeyFull$ = function (keys) {
20555         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20556             this._pathImageByKey,
20557             keys,
20558             this._propertiesKey
20559                 .concat(this._propertiesCore)
20560                 .concat(this._propertiesFill)
20561                 .concat(this._propertiesSpatial),
20562             this._propertiesKey
20563                 .concat(this._propertiesUser)
20564         ]))
20565             .map(function (value) {
20566             if (!value) {
20567                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20568             }
20569             return value.json.imageByKey;
20570         }), this._pathImageByKey, keys);
20571     };
20572     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
20573         var lonLat = lon + ":" + lat;
20574         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20575             this._pathImageCloseTo,
20576             [lonLat],
20577             this._propertiesKey
20578                 .concat(this._propertiesCore)
20579                 .concat(this._propertiesFill)
20580                 .concat(this._propertiesSpatial),
20581             this._propertiesKey
20582                 .concat(this._propertiesUser)
20583         ]))
20584             .map(function (value) {
20585             return value != null ? value.json.imageCloseTo[lonLat] : null;
20586         }), this._pathImageCloseTo, [lonLat]);
20587     };
20588     APIv3.prototype.imagesByH$ = function (hs) {
20589         var _this = this;
20590         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20591             this._pathImagesByH,
20592             hs,
20593             { from: 0, to: this._pageCount },
20594             this._propertiesKey
20595                 .concat(this._propertiesCore),
20596             this._propertiesKey
20597         ]))
20598             .map(function (value) {
20599             if (value == null) {
20600                 value = { json: { imagesByH: {} } };
20601                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
20602                     var h = hs_1[_i];
20603                     value.json.imagesByH[h] = {};
20604                     for (var i = 0; i <= _this._pageCount; i++) {
20605                         value.json.imagesByH[h][i] = null;
20606                     }
20607                 }
20608             }
20609             return value.json.imagesByH;
20610         }), this._pathImagesByH, hs);
20611     };
20612     APIv3.prototype.imageViewAdd$ = function (keys) {
20613         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
20614     };
20615     APIv3.prototype.invalidateImageByKey = function (keys) {
20616         this._invalidateGet(this._pathImageByKey, keys);
20617     };
20618     APIv3.prototype.invalidateImagesByH = function (hs) {
20619         this._invalidateGet(this._pathImagesByH, hs);
20620     };
20621     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
20622         this._invalidateGet(this._pathSequenceByKey, sKeys);
20623     };
20624     APIv3.prototype.setToken = function (token) {
20625         this._model.invalidate([]);
20626         this._model = null;
20627         this._model = this._modelCreator.createModel(this._clientId, token);
20628     };
20629     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
20630         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20631             this._pathSequenceByKey,
20632             sequenceKeys,
20633             this._propertiesKey
20634                 .concat(this._propertiesSequence)
20635         ]))
20636             .map(function (value) {
20637             return value.json.sequenceByKey;
20638         }), this._pathSequenceByKey, sequenceKeys);
20639     };
20640     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
20641         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
20642     };
20643     Object.defineProperty(APIv3.prototype, "clientId", {
20644         get: function () {
20645             return this._clientId;
20646         },
20647         enumerable: true,
20648         configurable: true
20649     });
20650     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
20651         var _this = this;
20652         return observable
20653             .catch(function (error) {
20654             _this._invalidateGet(path, paths);
20655             throw error;
20656         });
20657     };
20658     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
20659         var _this = this;
20660         return observable
20661             .catch(function (error) {
20662             _this._invalidateCall(path, paths);
20663             throw error;
20664         });
20665     };
20666     APIv3.prototype._invalidateGet = function (path, paths) {
20667         this._model.invalidate([path, paths]);
20668     };
20669     APIv3.prototype._invalidateCall = function (path, paths) {
20670         this._model.invalidate([path], [paths]);
20671     };
20672     APIv3.prototype._wrapPromise$ = function (promise) {
20673         return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
20674     };
20675     return APIv3;
20676 }());
20677 exports.APIv3 = APIv3;
20678 exports.default = APIv3;
20679
20680 },{"../API":229,"rxjs/Observable":29,"rxjs/add/observable/defer":39,"rxjs/add/observable/fromPromise":43,"rxjs/add/operator/catch":52,"rxjs/add/operator/map":65}],243:[function(require,module,exports){
20681 "use strict";
20682 /// <reference path="../../typings/index.d.ts" />
20683 Object.defineProperty(exports, "__esModule", { value: true });
20684 var falcor = require("falcor");
20685 var HttpDataSource = require("falcor-http-datasource");
20686 var Utils_1 = require("../Utils");
20687 /**
20688  * @class ModelCreator
20689  *
20690  * @classdesc Creates API models.
20691  */
20692 var ModelCreator = (function () {
20693     function ModelCreator() {
20694     }
20695     /**
20696      * Creates a Falcor model.
20697      *
20698      * @description Max cache size will be set to 16 MB. Authorization
20699      * header will be added if bearer token is supplied.
20700      *
20701      * @param {number} clientId - Client id for API requests.
20702      * @param {number} [token] - Optional bearer token for API requests of
20703      * protected resources.
20704      * @returns {falcor.Model} Falcor model for HTTP requests.
20705      */
20706     ModelCreator.prototype.createModel = function (clientId, token) {
20707         var configuration = {
20708             crossDomain: true,
20709             withCredentials: false,
20710         };
20711         if (token != null) {
20712             configuration.headers = { "Authorization": "Bearer " + token };
20713         }
20714         return new falcor.Model({
20715             maxSize: 16 * 1024 * 1024,
20716             source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
20717         });
20718     };
20719     return ModelCreator;
20720 }());
20721 exports.ModelCreator = ModelCreator;
20722 exports.default = ModelCreator;
20723
20724 },{"../Utils":240,"falcor":15,"falcor-http-datasource":10}],244:[function(require,module,exports){
20725 "use strict";
20726 /// <reference path="../../typings/index.d.ts" />
20727 var __extends = (this && this.__extends) || (function () {
20728     var extendStatics = Object.setPrototypeOf ||
20729         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20730         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20731     return function (d, b) {
20732         extendStatics(d, b);
20733         function __() { this.constructor = d; }
20734         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20735     };
20736 })();
20737 Object.defineProperty(exports, "__esModule", { value: true });
20738 var vd = require("virtual-dom");
20739 var Component_1 = require("../Component");
20740 var AttributionComponent = (function (_super) {
20741     __extends(AttributionComponent, _super);
20742     function AttributionComponent(name, container, navigator) {
20743         return _super.call(this, name, container, navigator) || this;
20744     }
20745     AttributionComponent.prototype._activate = function () {
20746         var _this = this;
20747         this._disposable = this._navigator.stateService.currentNode$
20748             .map(function (node) {
20749             return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
20750         })
20751             .subscribe(this._container.domRenderer.render$);
20752     };
20753     AttributionComponent.prototype._deactivate = function () {
20754         this._disposable.unsubscribe();
20755     };
20756     AttributionComponent.prototype._getDefaultConfiguration = function () {
20757         return {};
20758     };
20759     AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
20760         return vd.h("div.Attribution", {}, [
20761             vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
20762                 target: "_blank",
20763                 textContent: "@" + username,
20764             }, []),
20765             vd.h("span", { textContent: "|" }, []),
20766             vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
20767                 target: "_blank",
20768                 textContent: "mapillary.com",
20769             }, []),
20770         ]);
20771     };
20772     AttributionComponent.componentName = "attribution";
20773     return AttributionComponent;
20774 }(Component_1.Component));
20775 exports.AttributionComponent = AttributionComponent;
20776 Component_1.ComponentService.register(AttributionComponent);
20777 exports.default = AttributionComponent;
20778
20779 },{"../Component":230,"virtual-dom":186}],245:[function(require,module,exports){
20780 "use strict";
20781 /// <reference path="../../typings/index.d.ts" />
20782 var __extends = (this && this.__extends) || (function () {
20783     var extendStatics = Object.setPrototypeOf ||
20784         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20785         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20786     return function (d, b) {
20787         extendStatics(d, b);
20788         function __() { this.constructor = d; }
20789         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20790     };
20791 })();
20792 Object.defineProperty(exports, "__esModule", { value: true });
20793 var vd = require("virtual-dom");
20794 var Component_1 = require("../Component");
20795 var BackgroundComponent = (function (_super) {
20796     __extends(BackgroundComponent, _super);
20797     function BackgroundComponent(name, container, navigator) {
20798         return _super.call(this, name, container, navigator) || this;
20799     }
20800     BackgroundComponent.prototype._activate = function () {
20801         this._container.domRenderer.render$
20802             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
20803     };
20804     BackgroundComponent.prototype._deactivate = function () {
20805         return;
20806     };
20807     BackgroundComponent.prototype._getDefaultConfiguration = function () {
20808         return {};
20809     };
20810     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
20811         // todo: add condition for when to display the DOM node
20812         return vd.h("div.BackgroundWrapper", {}, [
20813             vd.h("p", { textContent: notice }, []),
20814         ]);
20815     };
20816     BackgroundComponent.componentName = "background";
20817     return BackgroundComponent;
20818 }(Component_1.Component));
20819 exports.BackgroundComponent = BackgroundComponent;
20820 Component_1.ComponentService.register(BackgroundComponent);
20821 exports.default = BackgroundComponent;
20822
20823 },{"../Component":230,"virtual-dom":186}],246:[function(require,module,exports){
20824 "use strict";
20825 /// <reference path="../../typings/index.d.ts" />
20826 var __extends = (this && this.__extends) || (function () {
20827     var extendStatics = Object.setPrototypeOf ||
20828         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20829         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20830     return function (d, b) {
20831         extendStatics(d, b);
20832         function __() { this.constructor = d; }
20833         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20834     };
20835 })();
20836 Object.defineProperty(exports, "__esModule", { value: true });
20837 var vd = require("virtual-dom");
20838 var Observable_1 = require("rxjs/Observable");
20839 var Component_1 = require("../Component");
20840 var Geo_1 = require("../Geo");
20841 var BearingComponent = (function (_super) {
20842     __extends(BearingComponent, _super);
20843     function BearingComponent(name, container, navigator) {
20844         var _this = _super.call(this, name, container, navigator) || this;
20845         _this._spatial = new Geo_1.Spatial();
20846         _this._svgNamespace = "http://www.w3.org/2000/svg";
20847         _this._distinctThreshold = Math.PI / 90;
20848         return _this;
20849     }
20850     BearingComponent.prototype._activate = function () {
20851         var _this = this;
20852         var nodeBearingFov$ = this._navigator.stateService.currentState$
20853             .distinctUntilChanged(undefined, function (frame) {
20854             return frame.state.currentNode.key;
20855         })
20856             .map(function (frame) {
20857             var node = frame.state.currentNode;
20858             var transform = frame.state.currentTransform;
20859             if (node.pano) {
20860                 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
20861                 return [_this._spatial.degToRad(node.ca), hFov_1];
20862             }
20863             var size = Math.max(transform.basicWidth, transform.basicHeight);
20864             if (size <= 0) {
20865                 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
20866                     "Not showing available fov.");
20867             }
20868             var hFov = size > 0 ?
20869                 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20870                 0;
20871             return [_this._spatial.degToRad(node.ca), hFov];
20872         })
20873             .distinctUntilChanged(function (a1, a2) {
20874             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20875                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20876         });
20877         var cameraBearingFov$ = this._container.renderService.renderCamera$
20878             .map(function (rc) {
20879             var vFov = _this._spatial.degToRad(rc.perspective.fov);
20880             var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
20881                 Math.PI :
20882                 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20883             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20884         })
20885             .distinctUntilChanged(function (a1, a2) {
20886             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20887                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20888         });
20889         this._renderSubscription = Observable_1.Observable
20890             .combineLatest(nodeBearingFov$, cameraBearingFov$)
20891             .map(function (args) {
20892             var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20893                 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20894                 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20895             ]);
20896             var north = vd.h("div.BearingIndicatorNorth", {}, []);
20897             var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20898             var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20899             var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20900             return {
20901                 name: _this._name,
20902                 vnode: vd.h("div.BearingIndicator", {}, [
20903                     background,
20904                     north,
20905                     compass,
20906                 ]),
20907             };
20908         })
20909             .subscribe(this._container.domRenderer.render$);
20910     };
20911     BearingComponent.prototype._deactivate = function () {
20912         this._renderSubscription.unsubscribe();
20913     };
20914     BearingComponent.prototype._getDefaultConfiguration = function () {
20915         return {};
20916     };
20917     BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20918         var group = vd.h("g", {
20919             attributes: { transform: "translate(1,1)" },
20920             namespace: this._svgNamespace,
20921         }, [nodeSector, cameraSector]);
20922         var centerCircle = vd.h("circle", {
20923             attributes: {
20924                 cx: "1",
20925                 cy: "1",
20926                 fill: "#abb1b9",
20927                 r: "0.291667",
20928                 stroke: "#000",
20929                 "stroke-width": "0.0833333",
20930             },
20931             namespace: this._svgNamespace,
20932         }, []);
20933         var svg = vd.h("svg", {
20934             attributes: { viewBox: "0 0 2 2" },
20935             namespace: this._svgNamespace,
20936             style: {
20937                 bottom: "4px",
20938                 height: "48px",
20939                 left: "4px",
20940                 position: "absolute",
20941                 width: "48px",
20942             },
20943         }, [group, centerCircle]);
20944         return svg;
20945     };
20946     BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20947         if (fov > 2 * Math.PI - Math.PI / 90) {
20948             return vd.h("circle", {
20949                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20950                 namespace: this._svgNamespace,
20951             }, []);
20952         }
20953         var arcStart = bearing - fov / 2 - Math.PI / 2;
20954         var arcEnd = arcStart + fov;
20955         var startX = Math.cos(arcStart);
20956         var startY = Math.sin(arcStart);
20957         var endX = Math.cos(arcEnd);
20958         var endY = Math.sin(arcEnd);
20959         var largeArc = fov >= Math.PI ? 1 : 0;
20960         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20961         return vd.h("path", {
20962             attributes: { d: description, fill: fill },
20963             namespace: this._svgNamespace,
20964         }, []);
20965     };
20966     BearingComponent.componentName = "bearing";
20967     return BearingComponent;
20968 }(Component_1.Component));
20969 exports.BearingComponent = BearingComponent;
20970 Component_1.ComponentService.register(BearingComponent);
20971 exports.default = BearingComponent;
20972
20973 },{"../Component":230,"../Geo":233,"rxjs/Observable":29,"virtual-dom":186}],247:[function(require,module,exports){
20974 "use strict";
20975 var __extends = (this && this.__extends) || (function () {
20976     var extendStatics = Object.setPrototypeOf ||
20977         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20978         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20979     return function (d, b) {
20980         extendStatics(d, b);
20981         function __() { this.constructor = d; }
20982         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20983     };
20984 })();
20985 Object.defineProperty(exports, "__esModule", { value: true });
20986 var Observable_1 = require("rxjs/Observable");
20987 require("rxjs/add/observable/combineLatest");
20988 require("rxjs/add/observable/from");
20989 require("rxjs/add/observable/merge");
20990 require("rxjs/add/observable/of");
20991 require("rxjs/add/observable/zip");
20992 require("rxjs/add/operator/catch");
20993 require("rxjs/add/operator/combineLatest");
20994 require("rxjs/add/operator/distinct");
20995 require("rxjs/add/operator/expand");
20996 require("rxjs/add/operator/filter");
20997 require("rxjs/add/operator/map");
20998 require("rxjs/add/operator/merge");
20999 require("rxjs/add/operator/mergeMap");
21000 require("rxjs/add/operator/mergeAll");
21001 require("rxjs/add/operator/skip");
21002 require("rxjs/add/operator/switchMap");
21003 var Edge_1 = require("../Edge");
21004 var Component_1 = require("../Component");
21005 var CacheComponent = (function (_super) {
21006     __extends(CacheComponent, _super);
21007     function CacheComponent(name, container, navigator) {
21008         return _super.call(this, name, container, navigator) || this;
21009     }
21010     /**
21011      * Set the cache depth.
21012      *
21013      * Configures the cache depth. The cache depth can be different for
21014      * different edge direction types.
21015      *
21016      * @param {ICacheDepth} depth - Cache depth structure.
21017      */
21018     CacheComponent.prototype.setDepth = function (depth) {
21019         this.configure({ depth: depth });
21020     };
21021     CacheComponent.prototype._activate = function () {
21022         var _this = this;
21023         this._sequenceSubscription = Observable_1.Observable
21024             .combineLatest(this._navigator.stateService.currentNode$
21025             .switchMap(function (node) {
21026             return node.sequenceEdges$;
21027         })
21028             .filter(function (status) {
21029             return status.cached;
21030         }), this._configuration$)
21031             .switchMap(function (nc) {
21032             var status = nc[0];
21033             var configuration = nc[1];
21034             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
21035             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
21036             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
21037             return Observable_1.Observable
21038                 .merge(next$, prev$)
21039                 .catch(function (error, caught) {
21040                 console.error("Failed to cache sequence edges.", error);
21041                 return Observable_1.Observable.empty();
21042             });
21043         })
21044             .subscribe(function () { });
21045         this._spatialSubscription = this._navigator.stateService.currentNode$
21046             .switchMap(function (node) {
21047             return Observable_1.Observable
21048                 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
21049                 .filter(function (status) {
21050                 return status.cached;
21051             }));
21052         })
21053             .combineLatest(this._configuration$, function (ns, configuration) {
21054             return [ns[0], ns[1], configuration];
21055         })
21056             .switchMap(function (args) {
21057             var node = args[0];
21058             var edges = args[1].edges;
21059             var depth = args[2].depth;
21060             var panoDepth = Math.max(0, Math.min(2, depth.pano));
21061             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
21062             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
21063             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
21064             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
21065             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
21066             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
21067             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
21068             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
21069             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
21070             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
21071             return Observable_1.Observable
21072                 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
21073                 .catch(function (error, caught) {
21074                 console.error("Failed to cache spatial edges.", error);
21075                 return Observable_1.Observable.empty();
21076             });
21077         })
21078             .subscribe(function () { });
21079     };
21080     CacheComponent.prototype._deactivate = function () {
21081         this._sequenceSubscription.unsubscribe();
21082         this._spatialSubscription.unsubscribe();
21083     };
21084     CacheComponent.prototype._getDefaultConfiguration = function () {
21085         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
21086     };
21087     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
21088         var _this = this;
21089         return Observable_1.Observable
21090             .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
21091             .expand(function (ed) {
21092             var es = ed[0];
21093             var d = ed[1];
21094             var edgesDepths$ = [];
21095             if (d > 0) {
21096                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
21097                     var edge = es_1[_i];
21098                     if (edge.data.direction === direction) {
21099                         edgesDepths$.push(Observable_1.Observable
21100                             .zip(_this._navigator.graphService.cacheNode$(edge.to)
21101                             .mergeMap(function (n) {
21102                             return _this._nodeToEdges$(n, direction);
21103                         }), Observable_1.Observable.of(d - 1)));
21104                     }
21105                 }
21106             }
21107             return Observable_1.Observable
21108                 .from(edgesDepths$)
21109                 .mergeAll();
21110         })
21111             .skip(1);
21112     };
21113     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
21114         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
21115             node.sequenceEdges$ :
21116             node.spatialEdges$)
21117             .first(function (status) {
21118             return status.cached;
21119         })
21120             .map(function (status) {
21121             return status.edges;
21122         });
21123     };
21124     CacheComponent.componentName = "cache";
21125     return CacheComponent;
21126 }(Component_1.Component));
21127 exports.CacheComponent = CacheComponent;
21128 Component_1.ComponentService.register(CacheComponent);
21129 exports.default = CacheComponent;
21130
21131 },{"../Component":230,"../Edge":231,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/expand":60,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeAll":67,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/skip":76,"rxjs/add/operator/switchMap":80}],248:[function(require,module,exports){
21132 "use strict";
21133 var __extends = (this && this.__extends) || (function () {
21134     var extendStatics = Object.setPrototypeOf ||
21135         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21136         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21137     return function (d, b) {
21138         extendStatics(d, b);
21139         function __() { this.constructor = d; }
21140         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21141     };
21142 })();
21143 Object.defineProperty(exports, "__esModule", { value: true });
21144 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
21145 var Subject_1 = require("rxjs/Subject");
21146 require("rxjs/add/operator/publishReplay");
21147 require("rxjs/add/operator/scan");
21148 require("rxjs/add/operator/startWith");
21149 var Utils_1 = require("../Utils");
21150 var Component = (function (_super) {
21151     __extends(Component, _super);
21152     function Component(name, container, navigator) {
21153         var _this = _super.call(this) || this;
21154         _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
21155         _this._configurationSubject$ = new Subject_1.Subject();
21156         _this._activated = false;
21157         _this._container = container;
21158         _this._name = name;
21159         _this._navigator = navigator;
21160         _this._configuration$ =
21161             _this._configurationSubject$
21162                 .startWith(_this.defaultConfiguration)
21163                 .scan(function (conf, newConf) {
21164                 for (var key in newConf) {
21165                     if (newConf.hasOwnProperty(key)) {
21166                         conf[key] = newConf[key];
21167                     }
21168                 }
21169                 return conf;
21170             })
21171                 .publishReplay(1)
21172                 .refCount();
21173         _this._configuration$.subscribe(function () { });
21174         return _this;
21175     }
21176     Object.defineProperty(Component.prototype, "activated", {
21177         get: function () {
21178             return this._activated;
21179         },
21180         enumerable: true,
21181         configurable: true
21182     });
21183     Object.defineProperty(Component.prototype, "activated$", {
21184         get: function () {
21185             return this._activated$;
21186         },
21187         enumerable: true,
21188         configurable: true
21189     });
21190     Object.defineProperty(Component.prototype, "defaultConfiguration", {
21191         /**
21192          * Get default configuration.
21193          *
21194          * @returns {TConfiguration} Default configuration for component.
21195          */
21196         get: function () {
21197             return this._getDefaultConfiguration();
21198         },
21199         enumerable: true,
21200         configurable: true
21201     });
21202     Object.defineProperty(Component.prototype, "configuration$", {
21203         get: function () {
21204             return this._configuration$;
21205         },
21206         enumerable: true,
21207         configurable: true
21208     });
21209     Object.defineProperty(Component.prototype, "name", {
21210         get: function () {
21211             return this._name;
21212         },
21213         enumerable: true,
21214         configurable: true
21215     });
21216     Component.prototype.activate = function (conf) {
21217         if (this._activated) {
21218             return;
21219         }
21220         if (conf !== undefined) {
21221             this._configurationSubject$.next(conf);
21222         }
21223         this._activated = true;
21224         this._activate();
21225         this._activated$.next(true);
21226     };
21227     Component.prototype.configure = function (conf) {
21228         this._configurationSubject$.next(conf);
21229     };
21230     Component.prototype.deactivate = function () {
21231         if (!this._activated) {
21232             return;
21233         }
21234         this._activated = false;
21235         this._deactivate();
21236         this._container.domRenderer.clear(this._name);
21237         this._container.glRenderer.clear(this._name);
21238         this._activated$.next(false);
21239     };
21240     /**
21241      * Detect the viewer's new width and height and resize the component's
21242      * rendered elements accordingly if applicable.
21243      */
21244     Component.prototype.resize = function () { return; };
21245     /**
21246      * Component name. Used when interacting with component through the Viewer's API.
21247      */
21248     Component.componentName = "not_worthy";
21249     return Component;
21250 }(Utils_1.EventEmitter));
21251 exports.Component = Component;
21252 exports.default = Component;
21253
21254 },{"../Utils":240,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/startWith":79}],249:[function(require,module,exports){
21255 "use strict";
21256 /// <reference path="../../typings/index.d.ts" />
21257 Object.defineProperty(exports, "__esModule", { value: true });
21258 var _ = require("underscore");
21259 var Error_1 = require("../Error");
21260 var ComponentService = (function () {
21261     function ComponentService(container, navigator) {
21262         this._components = {};
21263         this._container = container;
21264         this._navigator = navigator;
21265         for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
21266             var component = _a[_i];
21267             this._components[component.componentName] = {
21268                 active: false,
21269                 component: new component(component.componentName, container, navigator),
21270             };
21271         }
21272         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
21273         this._coverComponent.activate();
21274         this._coverActivated = true;
21275     }
21276     ComponentService.register = function (component) {
21277         if (ComponentService.registeredComponents[component.componentName] === undefined) {
21278             ComponentService.registeredComponents[component.componentName] = component;
21279         }
21280     };
21281     ComponentService.registerCover = function (coverComponent) {
21282         ComponentService.registeredCoverComponent = coverComponent;
21283     };
21284     Object.defineProperty(ComponentService.prototype, "coverActivated", {
21285         get: function () {
21286             return this._coverActivated;
21287         },
21288         enumerable: true,
21289         configurable: true
21290     });
21291     ComponentService.prototype.activateCover = function () {
21292         if (this._coverActivated) {
21293             return;
21294         }
21295         this._coverActivated = true;
21296         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21297             var component = _a[_i];
21298             if (component.active) {
21299                 component.component.deactivate();
21300             }
21301         }
21302         return;
21303     };
21304     ComponentService.prototype.deactivateCover = function () {
21305         if (!this._coverActivated) {
21306             return;
21307         }
21308         this._coverActivated = false;
21309         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21310             var component = _a[_i];
21311             if (component.active) {
21312                 component.component.activate();
21313             }
21314         }
21315         return;
21316     };
21317     ComponentService.prototype.activate = function (name) {
21318         this._checkName(name);
21319         this._components[name].active = true;
21320         if (!this._coverActivated) {
21321             this.get(name).activate();
21322         }
21323     };
21324     ComponentService.prototype.configure = function (name, conf) {
21325         this._checkName(name);
21326         this.get(name).configure(conf);
21327     };
21328     ComponentService.prototype.deactivate = function (name) {
21329         this._checkName(name);
21330         this._components[name].active = false;
21331         if (!this._coverActivated) {
21332             this.get(name).deactivate();
21333         }
21334     };
21335     ComponentService.prototype.resize = function () {
21336         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21337             var component = _a[_i];
21338             component.component.resize();
21339         }
21340     };
21341     ComponentService.prototype.get = function (name) {
21342         return this._components[name].component;
21343     };
21344     ComponentService.prototype.getCover = function () {
21345         return this._coverComponent;
21346     };
21347     ComponentService.prototype._checkName = function (name) {
21348         if (!(name in this._components)) {
21349             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
21350         }
21351     };
21352     ComponentService.registeredComponents = {};
21353     return ComponentService;
21354 }());
21355 exports.ComponentService = ComponentService;
21356 exports.default = ComponentService;
21357
21358 },{"../Error":232,"underscore":182}],250:[function(require,module,exports){
21359 "use strict";
21360 /// <reference path="../../typings/index.d.ts" />
21361 var __extends = (this && this.__extends) || (function () {
21362     var extendStatics = Object.setPrototypeOf ||
21363         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21364         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21365     return function (d, b) {
21366         extendStatics(d, b);
21367         function __() { this.constructor = d; }
21368         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21369     };
21370 })();
21371 Object.defineProperty(exports, "__esModule", { value: true });
21372 var vd = require("virtual-dom");
21373 require("rxjs/add/operator/filter");
21374 require("rxjs/add/operator/map");
21375 require("rxjs/add/operator/withLatestFrom");
21376 var Component_1 = require("../Component");
21377 var CoverComponent = (function (_super) {
21378     __extends(CoverComponent, _super);
21379     function CoverComponent(name, container, navigator) {
21380         return _super.call(this, name, container, navigator) || this;
21381     }
21382     CoverComponent.prototype._activate = function () {
21383         var _this = this;
21384         this._keyDisposable = this._navigator.stateService.currentNode$
21385             .withLatestFrom(this._configuration$, function (node, configuration) {
21386             return [node, configuration];
21387         })
21388             .filter(function (_a) {
21389             var node = _a[0], configuration = _a[1];
21390             return node.key !== configuration.key;
21391         })
21392             .map(function (_a) {
21393             var node = _a[0], configuration = _a[1];
21394             return node;
21395         })
21396             .map(function (node) {
21397             return { key: node.key, src: node.image.src };
21398         })
21399             .subscribe(this._configurationSubject$);
21400         this._disposable = this._configuration$
21401             .map(function (conf) {
21402             if (!conf.key) {
21403                 return { name: _this._name, vnode: vd.h("div", []) };
21404             }
21405             if (conf.state === Component_1.CoverState.Hidden) {
21406                 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
21407             }
21408             return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
21409         })
21410             .subscribe(this._container.domRenderer.render$);
21411     };
21412     CoverComponent.prototype._deactivate = function () {
21413         this._disposable.unsubscribe();
21414         this._keyDisposable.unsubscribe();
21415     };
21416     CoverComponent.prototype._getDefaultConfiguration = function () {
21417         return { state: Component_1.CoverState.Visible };
21418     };
21419     CoverComponent.prototype._getCoverButtonVNode = function (conf) {
21420         var _this = this;
21421         var cover = conf.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
21422         return vd.h(cover, [
21423             this._getCoverBackgroundVNode(conf),
21424             vd.h("button.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, ["Explore"]),
21425             vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
21426         ]);
21427     };
21428     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
21429         var url = conf.src != null ?
21430             "url(" + conf.src + ")" :
21431             "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
21432         var properties = { style: { backgroundImage: url } };
21433         var children = [];
21434         if (conf.state === Component_1.CoverState.Loading) {
21435             children.push(vd.h("div.Spinner", {}, []));
21436         }
21437         children.push(vd.h("div.CoverBackgroundGradient", {}, []));
21438         return vd.h("div.CoverBackground", properties, children);
21439     };
21440     CoverComponent.componentName = "cover";
21441     return CoverComponent;
21442 }(Component_1.Component));
21443 exports.CoverComponent = CoverComponent;
21444 Component_1.ComponentService.registerCover(CoverComponent);
21445 exports.default = CoverComponent;
21446
21447 },{"../Component":230,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":85,"virtual-dom":186}],251:[function(require,module,exports){
21448 "use strict";
21449 /// <reference path="../../typings/index.d.ts" />
21450 var __extends = (this && this.__extends) || (function () {
21451     var extendStatics = Object.setPrototypeOf ||
21452         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21453         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21454     return function (d, b) {
21455         extendStatics(d, b);
21456         function __() { this.constructor = d; }
21457         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21458     };
21459 })();
21460 Object.defineProperty(exports, "__esModule", { value: true });
21461 var _ = require("underscore");
21462 var vd = require("virtual-dom");
21463 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
21464 require("rxjs/add/operator/combineLatest");
21465 var Component_1 = require("../Component");
21466 var DebugComponent = (function (_super) {
21467     __extends(DebugComponent, _super);
21468     function DebugComponent(name, container, navigator) {
21469         var _this = _super.call(this, name, container, navigator) || this;
21470         _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
21471         _this._displaying = false;
21472         return _this;
21473     }
21474     DebugComponent.prototype._activate = function () {
21475         var _this = this;
21476         this._disposable = this._navigator.stateService.currentState$
21477             .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
21478             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
21479         })
21480             .subscribe(this._container.domRenderer.render$);
21481     };
21482     DebugComponent.prototype._deactivate = function () {
21483         this._disposable.unsubscribe();
21484     };
21485     DebugComponent.prototype._getDefaultConfiguration = function () {
21486         return {};
21487     };
21488     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
21489         var ret = [];
21490         ret.push(vd.h("h2", "Node"));
21491         if (frame.state.currentNode) {
21492             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
21493         }
21494         if (frame.state.previousNode) {
21495             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
21496         }
21497         ret.push(vd.h("h2", "Loading"));
21498         var total = 0;
21499         var loaded = 0;
21500         var loading = 0;
21501         for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21502             var loadStat = _a[_i];
21503             total += loadStat.loaded;
21504             if (loadStat.loaded !== loadStat.total) {
21505                 loading++;
21506             }
21507             else {
21508                 loaded++;
21509             }
21510         }
21511         ret.push(vd.h("p", "Loaded Images: " + loaded));
21512         ret.push(vd.h("p", "Loading Images: " + loading));
21513         ret.push(vd.h("p", "Total bytes loaded: " + total));
21514         ret.push(vd.h("h2", "Camera"));
21515         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
21516         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
21517         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
21518         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
21519         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
21520         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
21521         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
21522         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
21523         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
21524         return ret;
21525     };
21526     DebugComponent.prototype._getDebugVNode = function (open, info) {
21527         if (open) {
21528             return vd.h("div.Debug", {}, [
21529                 vd.h("h2", {}, ["Debug"]),
21530                 this._getDebugVNodeButton(open),
21531                 vd.h("pre", {}, info),
21532             ]);
21533         }
21534         else {
21535             return this._getDebugVNodeButton(open);
21536         }
21537     };
21538     DebugComponent.prototype._getDebugVNodeButton = function (open) {
21539         var buttonText = open ? "Disable Debug" : "D";
21540         var buttonCssClass = open ? "" : ".DebugButtonFixed";
21541         if (open) {
21542             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
21543         }
21544         else {
21545             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
21546         }
21547     };
21548     DebugComponent.prototype._closeDebugElement = function (open) {
21549         this._open$.next(false);
21550     };
21551     DebugComponent.prototype._openDebugElement = function () {
21552         this._open$.next(true);
21553     };
21554     DebugComponent.componentName = "debug";
21555     return DebugComponent;
21556 }(Component_1.Component));
21557 exports.DebugComponent = DebugComponent;
21558 Component_1.ComponentService.register(DebugComponent);
21559 exports.default = DebugComponent;
21560
21561 },{"../Component":230,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":53,"underscore":182,"virtual-dom":186}],252:[function(require,module,exports){
21562 "use strict";
21563 /// <reference path="../../typings/index.d.ts" />
21564 var __extends = (this && this.__extends) || (function () {
21565     var extendStatics = Object.setPrototypeOf ||
21566         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21567         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21568     return function (d, b) {
21569         extendStatics(d, b);
21570         function __() { this.constructor = d; }
21571         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21572     };
21573 })();
21574 Object.defineProperty(exports, "__esModule", { value: true });
21575 var vd = require("virtual-dom");
21576 var Observable_1 = require("rxjs/Observable");
21577 require("rxjs/add/operator/combineLatest");
21578 var Component_1 = require("../Component");
21579 var Utils_1 = require("../Utils");
21580 var ImageComponent = (function (_super) {
21581     __extends(ImageComponent, _super);
21582     function ImageComponent(name, container, navigator, dom) {
21583         var _this = _super.call(this, name, container, navigator) || this;
21584         _this._canvasId = container.id + "-" + _this._name;
21585         _this._dom = !!dom ? dom : new Utils_1.DOM();
21586         return _this;
21587     }
21588     ImageComponent.prototype._activate = function () {
21589         var _this = this;
21590         var canvasSize$ = this._container.domRenderer.element$
21591             .map(function (element) {
21592             return _this._dom.document.getElementById(_this._canvasId);
21593         })
21594             .filter(function (canvas) {
21595             return !!canvas;
21596         })
21597             .map(function (canvas) {
21598             var adaptableDomRenderer = canvas.parentElement;
21599             var width = adaptableDomRenderer.offsetWidth;
21600             var height = adaptableDomRenderer.offsetHeight;
21601             return [canvas, { height: height, width: width }];
21602         })
21603             .distinctUntilChanged(function (s1, s2) {
21604             return s1.height === s2.height && s1.width === s2.width;
21605         }, function (_a) {
21606             var canvas = _a[0], size = _a[1];
21607             return size;
21608         });
21609         this.drawSubscription = Observable_1.Observable
21610             .combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
21611             .subscribe(function (_a) {
21612             var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
21613             canvas.width = size.width;
21614             canvas.height = size.height;
21615             canvas
21616                 .getContext("2d")
21617                 .drawImage(node.image, 0, 0, size.width, size.height);
21618         });
21619         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
21620     };
21621     ImageComponent.prototype._deactivate = function () {
21622         this.drawSubscription.unsubscribe();
21623     };
21624     ImageComponent.prototype._getDefaultConfiguration = function () {
21625         return {};
21626     };
21627     ImageComponent.componentName = "image";
21628     return ImageComponent;
21629 }(Component_1.Component));
21630 exports.ImageComponent = ImageComponent;
21631 Component_1.ComponentService.register(ImageComponent);
21632 exports.default = ImageComponent;
21633
21634 },{"../Component":230,"../Utils":240,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":53,"virtual-dom":186}],253:[function(require,module,exports){
21635 "use strict";
21636 /// <reference path="../../typings/index.d.ts" />
21637 var __extends = (this && this.__extends) || (function () {
21638     var extendStatics = Object.setPrototypeOf ||
21639         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21640         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21641     return function (d, b) {
21642         extendStatics(d, b);
21643         function __() { this.constructor = d; }
21644         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21645     };
21646 })();
21647 Object.defineProperty(exports, "__esModule", { value: true });
21648 var _ = require("underscore");
21649 var vd = require("virtual-dom");
21650 require("rxjs/add/operator/combineLatest");
21651 var Component_1 = require("../Component");
21652 var LoadingComponent = (function (_super) {
21653     __extends(LoadingComponent, _super);
21654     function LoadingComponent(name, container, navigator) {
21655         return _super.call(this, name, container, navigator) || this;
21656     }
21657     LoadingComponent.prototype._activate = function () {
21658         var _this = this;
21659         this._loadingSubscription = this._navigator.loadingService.loading$
21660             .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
21661             if (!loading) {
21662                 return { name: "loading", vnode: _this._getBarVNode(100) };
21663             }
21664             var total = 0;
21665             var loaded = 0;
21666             for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21667                 var loadStat = _a[_i];
21668                 if (loadStat.loaded !== loadStat.total) {
21669                     loaded += loadStat.loaded;
21670                     total += loadStat.total;
21671                 }
21672             }
21673             var percentage = 100;
21674             if (total !== 0) {
21675                 percentage = (loaded / total) * 100;
21676             }
21677             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
21678         })
21679             .subscribe(this._container.domRenderer.render$);
21680     };
21681     LoadingComponent.prototype._deactivate = function () {
21682         this._loadingSubscription.unsubscribe();
21683     };
21684     LoadingComponent.prototype._getDefaultConfiguration = function () {
21685         return {};
21686     };
21687     LoadingComponent.prototype._getBarVNode = function (percentage) {
21688         var loadingBarStyle = {};
21689         var loadingContainerStyle = {};
21690         if (percentage !== 100) {
21691             loadingBarStyle.width = percentage.toFixed(0) + "%";
21692             loadingBarStyle.opacity = "1";
21693         }
21694         else {
21695             loadingBarStyle.width = "100%";
21696             loadingBarStyle.opacity = "0";
21697         }
21698         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
21699     };
21700     LoadingComponent.componentName = "loading";
21701     return LoadingComponent;
21702 }(Component_1.Component));
21703 exports.LoadingComponent = LoadingComponent;
21704 Component_1.ComponentService.register(LoadingComponent);
21705 exports.default = LoadingComponent;
21706
21707 },{"../Component":230,"rxjs/add/operator/combineLatest":53,"underscore":182,"virtual-dom":186}],254:[function(require,module,exports){
21708 "use strict";
21709 /// <reference path="../../typings/index.d.ts" />
21710 var __extends = (this && this.__extends) || (function () {
21711     var extendStatics = Object.setPrototypeOf ||
21712         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21713         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21714     return function (d, b) {
21715         extendStatics(d, b);
21716         function __() { this.constructor = d; }
21717         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21718     };
21719 })();
21720 Object.defineProperty(exports, "__esModule", { value: true });
21721 var vd = require("virtual-dom");
21722 var Observable_1 = require("rxjs/Observable");
21723 require("rxjs/add/operator/map");
21724 require("rxjs/add/operator/first");
21725 var Edge_1 = require("../Edge");
21726 var Component_1 = require("../Component");
21727 /**
21728  * @class NavigationComponent
21729  *
21730  * @classdesc Fallback navigation component for environments without WebGL support.
21731  *
21732  * Replaces the functionality in the Direction and Sequence components.
21733  */
21734 var NavigationComponent = (function (_super) {
21735     __extends(NavigationComponent, _super);
21736     function NavigationComponent(name, container, navigator) {
21737         var _this = _super.call(this, name, container, navigator) || this;
21738         _this._seqNames = {};
21739         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
21740         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
21741         _this._spaTopNames = {};
21742         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
21743         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
21744         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
21745         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
21746         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
21747         _this._spaBottomNames = {};
21748         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
21749         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
21750         return _this;
21751     }
21752     NavigationComponent.prototype._activate = function () {
21753         var _this = this;
21754         this._renderSubscription = Observable_1.Observable
21755             .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
21756             .switchMap(function (_a) {
21757             var node = _a[0], configuration = _a[1];
21758             var sequenceEdges$ = configuration.sequence ?
21759                 node.sequenceEdges$
21760                     .map(function (status) {
21761                     return status.edges
21762                         .map(function (edge) {
21763                         return edge.data.direction;
21764                     });
21765                 }) :
21766                 Observable_1.Observable.of([]);
21767             var spatialEdges$ = !node.pano && configuration.spatial ?
21768                 node.spatialEdges$
21769                     .map(function (status) {
21770                     return status.edges
21771                         .map(function (edge) {
21772                         return edge.data.direction;
21773                     });
21774                 }) :
21775                 Observable_1.Observable.of([]);
21776             return Observable_1.Observable
21777                 .combineLatest(sequenceEdges$, spatialEdges$)
21778                 .map(function (_a) {
21779                 var seq = _a[0], spa = _a[1];
21780                 return seq.concat(spa);
21781             });
21782         })
21783             .map(function (edgeDirections) {
21784             var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
21785             var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
21786             var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
21787             var seqContainer = vd.h("div.NavigationSequence", seqs);
21788             var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
21789             var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
21790             var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
21791             return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
21792         })
21793             .subscribe(this._container.domRenderer.render$);
21794     };
21795     NavigationComponent.prototype._deactivate = function () {
21796         this._renderSubscription.unsubscribe();
21797     };
21798     NavigationComponent.prototype._getDefaultConfiguration = function () {
21799         return { sequence: true, spatial: true };
21800     };
21801     NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
21802         var arrows = [];
21803         for (var arrowName in arrowNames) {
21804             if (!(arrowNames.hasOwnProperty(arrowName))) {
21805                 continue;
21806             }
21807             var direction = Edge_1.EdgeDirection[arrowName];
21808             if (edgeDirections.indexOf(direction) !== -1) {
21809                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
21810             }
21811             else {
21812                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
21813             }
21814         }
21815         return arrows;
21816     };
21817     NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
21818         var _this = this;
21819         return vd.h("span.Direction.Direction" + name, {
21820             onclick: function (ev) {
21821                 _this._navigator.moveDir$(direction)
21822                     .subscribe(function (node) { return; }, function (error) { console.error(error); });
21823             },
21824             style: {
21825                 visibility: visibility,
21826             },
21827         }, []);
21828     };
21829     NavigationComponent.componentName = "navigation";
21830     return NavigationComponent;
21831 }(Component_1.Component));
21832 exports.NavigationComponent = NavigationComponent;
21833 Component_1.ComponentService.register(NavigationComponent);
21834 exports.default = NavigationComponent;
21835
21836 },{"../Component":230,"../Edge":231,"rxjs/Observable":29,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"virtual-dom":186}],255:[function(require,module,exports){
21837 "use strict";
21838 /// <reference path="../../typings/index.d.ts" />
21839 var __extends = (this && this.__extends) || (function () {
21840     var extendStatics = Object.setPrototypeOf ||
21841         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21842         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21843     return function (d, b) {
21844         extendStatics(d, b);
21845         function __() { this.constructor = d; }
21846         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21847     };
21848 })();
21849 Object.defineProperty(exports, "__esModule", { value: true });
21850 var _ = require("underscore");
21851 var vd = require("virtual-dom");
21852 var Observable_1 = require("rxjs/Observable");
21853 require("rxjs/add/observable/fromPromise");
21854 require("rxjs/add/observable/of");
21855 require("rxjs/add/operator/combineLatest");
21856 require("rxjs/add/operator/distinct");
21857 require("rxjs/add/operator/distinctUntilChanged");
21858 require("rxjs/add/operator/filter");
21859 require("rxjs/add/operator/map");
21860 require("rxjs/add/operator/mergeMap");
21861 require("rxjs/add/operator/pluck");
21862 require("rxjs/add/operator/scan");
21863 var Component_1 = require("../Component");
21864 var DescriptionState = (function () {
21865     function DescriptionState() {
21866     }
21867     return DescriptionState;
21868 }());
21869 var RouteState = (function () {
21870     function RouteState() {
21871     }
21872     return RouteState;
21873 }());
21874 var RouteTrack = (function () {
21875     function RouteTrack() {
21876         this.nodeInstructions = [];
21877         this.nodeInstructionsOrdered = [];
21878     }
21879     return RouteTrack;
21880 }());
21881 var RouteComponent = (function (_super) {
21882     __extends(RouteComponent, _super);
21883     function RouteComponent(name, container, navigator) {
21884         return _super.call(this, name, container, navigator) || this;
21885     }
21886     RouteComponent.prototype._activate = function () {
21887         var _this = this;
21888         var _slowedStream$;
21889         _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21890             return (frame.id % 2) === 0;
21891         }).filter(function (frame) {
21892             return frame.state.nodesAhead < 15;
21893         }).distinctUntilChanged(undefined, function (frame) {
21894             return frame.state.lastNode.key;
21895         });
21896         var _routeTrack$;
21897         _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21898             return Observable_1.Observable.from(conf.paths);
21899         }).distinct(function (p) {
21900             return p.sequenceKey;
21901         }).mergeMap(function (path) {
21902             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21903                 .map(function (sequenceByKey) {
21904                 return sequenceByKey[path.sequenceKey];
21905             });
21906         }).combineLatest(this.configuration$, function (sequence, conf) {
21907             var i = 0;
21908             var instructionPlaces = [];
21909             for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21910                 var path = _a[_i];
21911                 if (path.sequenceKey === sequence.key) {
21912                     var nodeInstructions = [];
21913                     var saveKey = false;
21914                     for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21915                         var key = _c[_b];
21916                         if (path.startKey === key) {
21917                             saveKey = true;
21918                         }
21919                         if (saveKey) {
21920                             var description = null;
21921                             for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21922                                 var infoKey = _e[_d];
21923                                 if (infoKey.key === key) {
21924                                     description = infoKey.description;
21925                                 }
21926                             }
21927                             nodeInstructions.push({ description: description, key: key });
21928                         }
21929                         if (path.stopKey === key) {
21930                             saveKey = false;
21931                         }
21932                     }
21933                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21934                 }
21935                 i++;
21936             }
21937             return instructionPlaces;
21938         }).scan(function (routeTrack, instructionPlaces) {
21939             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21940                 var instructionPlace = instructionPlaces_1[_i];
21941                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21942             }
21943             routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21944             return routeTrack;
21945         }, new RouteTrack());
21946         this._disposable = _slowedStream$
21947             .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21948             return { conf: conf, frame: frame, routeTrack: routeTrack };
21949         }).scan(function (routeState, rtAndFrame) {
21950             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21951                 routeState.routeTrack = rtAndFrame.routeTrack;
21952                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21953                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21954                 routeState.playing = true;
21955             }
21956             else {
21957                 _this._navigator.stateService.cutNodes();
21958                 routeState.playing = false;
21959             }
21960             return routeState;
21961         }, new RouteState())
21962             .filter(function (routeState) {
21963             return routeState.playing;
21964         }).filter(function (routeState) {
21965             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21966                 var nodeInstruction = _a[_i];
21967                 if (!nodeInstruction) {
21968                     continue;
21969                 }
21970                 if (nodeInstruction.key === routeState.lastNode.key) {
21971                     return true;
21972                 }
21973             }
21974             return false;
21975         }).distinctUntilChanged(undefined, function (routeState) {
21976             return routeState.lastNode.key;
21977         }).mergeMap(function (routeState) {
21978             var i = 0;
21979             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21980                 var nodeInstruction = _a[_i];
21981                 if (nodeInstruction.key === routeState.lastNode.key) {
21982                     break;
21983                 }
21984                 i++;
21985             }
21986             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21987             if (!nextInstruction) {
21988                 return Observable_1.Observable.of(null);
21989             }
21990             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21991         }).combineLatest(this.configuration$, function (node, conf) {
21992             return { conf: conf, node: node };
21993         }).filter(function (cAN) {
21994             return cAN.node !== null && cAN.conf.playing;
21995         }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21996         this._disposableDescription = this._navigator.stateService.currentNode$
21997             .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21998             if (conf.playing !== undefined && !conf.playing) {
21999                 return "quit";
22000             }
22001             var description = null;
22002             for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
22003                 var nodeInstruction = _a[_i];
22004                 if (nodeInstruction.key === node.key) {
22005                     description = nodeInstruction.description;
22006                     break;
22007                 }
22008             }
22009             return description;
22010         }).scan(function (descriptionState, description) {
22011             if (description !== descriptionState.description && description !== null) {
22012                 descriptionState.description = description;
22013                 descriptionState.showsLeft = 6;
22014             }
22015             else {
22016                 descriptionState.showsLeft--;
22017             }
22018             if (description === "quit") {
22019                 descriptionState.description = null;
22020             }
22021             return descriptionState;
22022         }, new DescriptionState()).map(function (descriptionState) {
22023             if (descriptionState.showsLeft > 0 && descriptionState.description) {
22024                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
22025             }
22026             else {
22027                 return { name: _this._name, vnode: vd.h("div", []) };
22028             }
22029         }).subscribe(this._container.domRenderer.render$);
22030     };
22031     RouteComponent.prototype._deactivate = function () {
22032         this._disposable.unsubscribe();
22033         this._disposableDescription.unsubscribe();
22034     };
22035     RouteComponent.prototype._getDefaultConfiguration = function () {
22036         return {};
22037     };
22038     RouteComponent.prototype.play = function () {
22039         this.configure({ playing: true });
22040     };
22041     RouteComponent.prototype.stop = function () {
22042         this.configure({ playing: false });
22043     };
22044     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
22045         return vd.h("div.RouteFrame", {}, [
22046             vd.h("p", { textContent: description }, []),
22047         ]);
22048     };
22049     RouteComponent.componentName = "route";
22050     return RouteComponent;
22051 }(Component_1.Component));
22052 exports.RouteComponent = RouteComponent;
22053 Component_1.ComponentService.register(RouteComponent);
22054 exports.default = RouteComponent;
22055
22056 },{"../Component":230,"rxjs/Observable":29,"rxjs/add/observable/fromPromise":43,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":74,"underscore":182,"virtual-dom":186}],256:[function(require,module,exports){
22057 "use strict";
22058 var __extends = (this && this.__extends) || (function () {
22059     var extendStatics = Object.setPrototypeOf ||
22060         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22061         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22062     return function (d, b) {
22063         extendStatics(d, b);
22064         function __() { this.constructor = d; }
22065         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22066     };
22067 })();
22068 Object.defineProperty(exports, "__esModule", { value: true });
22069 var Observable_1 = require("rxjs/Observable");
22070 require("rxjs/add/operator/buffer");
22071 require("rxjs/add/operator/debounceTime");
22072 require("rxjs/add/operator/filter");
22073 require("rxjs/add/operator/map");
22074 require("rxjs/add/operator/scan");
22075 var Component_1 = require("../Component");
22076 var StatsComponent = (function (_super) {
22077     __extends(StatsComponent, _super);
22078     function StatsComponent(name, container, navigator) {
22079         return _super.call(this, name, container, navigator) || this;
22080     }
22081     StatsComponent.prototype._activate = function () {
22082         var _this = this;
22083         this._sequenceSubscription = this._navigator.stateService.currentNode$
22084             .scan(function (keys, node) {
22085             var sKey = node.sequenceKey;
22086             keys.report = [];
22087             if (!(sKey in keys.reported)) {
22088                 keys.report = [sKey];
22089                 keys.reported[sKey] = true;
22090             }
22091             return keys;
22092         }, { report: [], reported: {} })
22093             .filter(function (keys) {
22094             return keys.report.length > 0;
22095         })
22096             .mergeMap(function (keys) {
22097             return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
22098                 .catch(function (error, caught) {
22099                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
22100                 return Observable_1.Observable.empty();
22101             });
22102         })
22103             .subscribe(function () { });
22104         this._imageSubscription = this._navigator.stateService.currentNode$
22105             .map(function (node) {
22106             return node.key;
22107         })
22108             .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
22109             .scan(function (keys, newKeys) {
22110             keys.report = [];
22111             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
22112                 var key = newKeys_1[_i];
22113                 if (!(key in keys.reported)) {
22114                     keys.report.push(key);
22115                     keys.reported[key] = true;
22116                 }
22117             }
22118             return keys;
22119         }, { report: [], reported: {} })
22120             .filter(function (keys) {
22121             return keys.report.length > 0;
22122         })
22123             .mergeMap(function (keys) {
22124             return _this._navigator.apiV3.imageViewAdd$(keys.report)
22125                 .catch(function (error, caught) {
22126                 console.error("Failed to report image stats (" + keys.report + ")", error);
22127                 return Observable_1.Observable.empty();
22128             });
22129         })
22130             .subscribe(function () { });
22131     };
22132     StatsComponent.prototype._deactivate = function () {
22133         this._sequenceSubscription.unsubscribe();
22134         this._imageSubscription.unsubscribe();
22135     };
22136     StatsComponent.prototype._getDefaultConfiguration = function () {
22137         return {};
22138     };
22139     StatsComponent.componentName = "stats";
22140     return StatsComponent;
22141 }(Component_1.Component));
22142 exports.StatsComponent = StatsComponent;
22143 Component_1.ComponentService.register(StatsComponent);
22144 exports.default = StatsComponent;
22145
22146 },{"../Component":230,"rxjs/Observable":29,"rxjs/add/operator/buffer":49,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":74}],257:[function(require,module,exports){
22147 "use strict";
22148 /// <reference path="../../../typings/index.d.ts" />
22149 var __extends = (this && this.__extends) || (function () {
22150     var extendStatics = Object.setPrototypeOf ||
22151         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22152         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22153     return function (d, b) {
22154         extendStatics(d, b);
22155         function __() { this.constructor = d; }
22156         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22157     };
22158 })();
22159 Object.defineProperty(exports, "__esModule", { value: true });
22160 var vd = require("virtual-dom");
22161 var Observable_1 = require("rxjs/Observable");
22162 var Subject_1 = require("rxjs/Subject");
22163 require("rxjs/add/observable/combineLatest");
22164 require("rxjs/add/operator/do");
22165 require("rxjs/add/operator/distinctUntilChanged");
22166 require("rxjs/add/operator/filter");
22167 require("rxjs/add/operator/map");
22168 require("rxjs/add/operator/share");
22169 var Component_1 = require("../../Component");
22170 /**
22171  * @class DirectionComponent
22172  * @classdesc Component showing navigation arrows for steps and turns.
22173  */
22174 var DirectionComponent = (function (_super) {
22175     __extends(DirectionComponent, _super);
22176     function DirectionComponent(name, container, navigator, directionDOMRenderer) {
22177         var _this = _super.call(this, name, container, navigator) || this;
22178         _this._renderer = !!directionDOMRenderer ?
22179             directionDOMRenderer :
22180             new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
22181         _this._hoveredKeySubject$ = new Subject_1.Subject();
22182         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
22183         return _this;
22184     }
22185     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
22186         /**
22187          * Get hovered key observable.
22188          *
22189          * @description An observable emitting the key of the node for the direction
22190          * arrow that is being hovered. When the mouse leaves a direction arrow null
22191          * is emitted.
22192          *
22193          * @returns {Observable<string>}
22194          */
22195         get: function () {
22196             return this._hoveredKey$;
22197         },
22198         enumerable: true,
22199         configurable: true
22200     });
22201     /**
22202      * Set highlight key.
22203      *
22204      * @description The arrow pointing towards the node corresponding to the
22205      * highlight key will be highlighted.
22206      *
22207      * @param {string} highlightKey Key of node to be highlighted if existing
22208      * among arrows.
22209      */
22210     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
22211         this.configure({ highlightKey: highlightKey });
22212     };
22213     /**
22214      * Set min width of container element.
22215      *
22216      * @description  Set min width of the non transformed container element holding
22217      * the navigation arrows. If the min width is larger than the max width the
22218      * min width value will be used.
22219      *
22220      * The container element is automatically resized when the resize
22221      * method on the Viewer class is called.
22222      *
22223      * @param {number} minWidth
22224      */
22225     DirectionComponent.prototype.setMinWidth = function (minWidth) {
22226         this.configure({ minWidth: minWidth });
22227     };
22228     /**
22229      * Set max width of container element.
22230      *
22231      * @description Set max width of the non transformed container element holding
22232      * the navigation arrows. If the min width is larger than the max width the
22233      * min width value will be used.
22234      *
22235      * The container element is automatically resized when the resize
22236      * method on the Viewer class is called.
22237      *
22238      * @param {number} minWidth
22239      */
22240     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
22241         this.configure({ maxWidth: maxWidth });
22242     };
22243     /** @inheritdoc */
22244     DirectionComponent.prototype.resize = function () {
22245         this._renderer.resize(this._container.element);
22246     };
22247     DirectionComponent.prototype._activate = function () {
22248         var _this = this;
22249         this._configurationSubscription = this._configuration$
22250             .subscribe(function (configuration) {
22251             _this._renderer.setConfiguration(configuration);
22252         });
22253         this._nodeSubscription = this._navigator.stateService.currentNode$
22254             .do(function (node) {
22255             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
22256             _this._renderer.setNode(node);
22257         })
22258             .withLatestFrom(this._configuration$)
22259             .switchMap(function (_a) {
22260             var node = _a[0], configuration = _a[1];
22261             return Observable_1.Observable
22262                 .combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
22263                 _this._navigator.graphService
22264                     .cacheSequence$(node.sequenceKey)
22265                     .catch(function (error, caught) {
22266                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
22267                     return Observable_1.Observable.of(null);
22268                 }) :
22269                 Observable_1.Observable.of(null));
22270         })
22271             .subscribe(function (_a) {
22272             var edgeStatus = _a[0], sequence = _a[1];
22273             _this._renderer.setEdges(edgeStatus, sequence);
22274         });
22275         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
22276             .do(function (renderCamera) {
22277             _this._renderer.setRenderCamera(renderCamera);
22278         })
22279             .map(function (renderCamera) {
22280             return _this._renderer;
22281         })
22282             .filter(function (renderer) {
22283             return renderer.needsRender;
22284         })
22285             .map(function (renderer) {
22286             return { name: _this._name, vnode: renderer.render(_this._navigator) };
22287         })
22288             .subscribe(this._container.domRenderer.render$);
22289         this._hoveredKeySubscription = Observable_1.Observable
22290             .combineLatest([
22291             this._container.domRenderer.element$,
22292             this._container.renderService.renderCamera$,
22293             this._container.mouseService.mouseMove$.startWith(null),
22294             this._container.mouseService.mouseUp$.startWith(null),
22295         ], function (e, rc, mm, mu) {
22296             return e;
22297         })
22298             .map(function (element) {
22299             var elements = element.getElementsByClassName("DirectionsPerspective");
22300             for (var i = 0; i < elements.length; i++) {
22301                 var hovered = elements.item(i).querySelector(":hover");
22302                 if (hovered != null && hovered.hasAttribute("data-key")) {
22303                     return hovered.getAttribute("data-key");
22304                 }
22305             }
22306             return null;
22307         })
22308             .distinctUntilChanged()
22309             .subscribe(this._hoveredKeySubject$);
22310     };
22311     DirectionComponent.prototype._deactivate = function () {
22312         this._configurationSubscription.unsubscribe();
22313         this._nodeSubscription.unsubscribe();
22314         this._renderCameraSubscription.unsubscribe();
22315         this._hoveredKeySubscription.unsubscribe();
22316     };
22317     DirectionComponent.prototype._getDefaultConfiguration = function () {
22318         return {
22319             distinguishSequence: false,
22320             maxWidth: 460,
22321             minWidth: 260,
22322         };
22323     };
22324     /** @inheritdoc */
22325     DirectionComponent.componentName = "direction";
22326     return DirectionComponent;
22327 }(Component_1.Component));
22328 exports.DirectionComponent = DirectionComponent;
22329 Component_1.ComponentService.register(DirectionComponent);
22330 exports.default = DirectionComponent;
22331
22332 },{"../../Component":230,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/share":75,"virtual-dom":186}],258:[function(require,module,exports){
22333 "use strict";
22334 Object.defineProperty(exports, "__esModule", { value: true });
22335 var Geo_1 = require("../../Geo");
22336 /**
22337  * @class DirectionDOMCalculator
22338  * @classdesc Helper class for calculating DOM CSS properties.
22339  */
22340 var DirectionDOMCalculator = (function () {
22341     function DirectionDOMCalculator(configuration, element) {
22342         this._spatial = new Geo_1.Spatial();
22343         this._minThresholdWidth = 320;
22344         this._maxThresholdWidth = 1480;
22345         this._minThresholdHeight = 240;
22346         this._maxThresholdHeight = 820;
22347         this._configure(configuration);
22348         this._resize(element);
22349         this._reset();
22350     }
22351     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
22352         get: function () {
22353             return this._minWidth;
22354         },
22355         enumerable: true,
22356         configurable: true
22357     });
22358     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
22359         get: function () {
22360             return this._maxWidth;
22361         },
22362         enumerable: true,
22363         configurable: true
22364     });
22365     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
22366         get: function () {
22367             return this._containerWidth;
22368         },
22369         enumerable: true,
22370         configurable: true
22371     });
22372     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
22373         get: function () {
22374             return this._containerWidthCss;
22375         },
22376         enumerable: true,
22377         configurable: true
22378     });
22379     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
22380         get: function () {
22381             return this._containerMarginCss;
22382         },
22383         enumerable: true,
22384         configurable: true
22385     });
22386     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
22387         get: function () {
22388             return this._containerLeftCss;
22389         },
22390         enumerable: true,
22391         configurable: true
22392     });
22393     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
22394         get: function () {
22395             return this._containerHeight;
22396         },
22397         enumerable: true,
22398         configurable: true
22399     });
22400     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
22401         get: function () {
22402             return this._containerHeightCss;
22403         },
22404         enumerable: true,
22405         configurable: true
22406     });
22407     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
22408         get: function () {
22409             return this._containerBottomCss;
22410         },
22411         enumerable: true,
22412         configurable: true
22413     });
22414     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
22415         get: function () {
22416             return this._stepCircleSize;
22417         },
22418         enumerable: true,
22419         configurable: true
22420     });
22421     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
22422         get: function () {
22423             return this._stepCircleSizeCss;
22424         },
22425         enumerable: true,
22426         configurable: true
22427     });
22428     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
22429         get: function () {
22430             return this._stepCircleMarginCss;
22431         },
22432         enumerable: true,
22433         configurable: true
22434     });
22435     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
22436         get: function () {
22437             return this._turnCircleSize;
22438         },
22439         enumerable: true,
22440         configurable: true
22441     });
22442     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
22443         get: function () {
22444             return this._turnCircleSizeCss;
22445         },
22446         enumerable: true,
22447         configurable: true
22448     });
22449     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
22450         get: function () {
22451             return this._outerRadius;
22452         },
22453         enumerable: true,
22454         configurable: true
22455     });
22456     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
22457         get: function () {
22458             return this._innerRadius;
22459         },
22460         enumerable: true,
22461         configurable: true
22462     });
22463     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
22464         get: function () {
22465             return this._shadowOffset;
22466         },
22467         enumerable: true,
22468         configurable: true
22469     });
22470     /**
22471      * Configures the min and max width values.
22472      *
22473      * @param {IDirectionConfiguration} configuration Configuration
22474      * with min and max width values.
22475      */
22476     DirectionDOMCalculator.prototype.configure = function (configuration) {
22477         this._configure(configuration);
22478         this._reset();
22479     };
22480     /**
22481      * Resizes all properties according to the width and height
22482      * of the element.
22483      *
22484      * @param {HTMLElement} element The container element from which to extract
22485      * the width and height.
22486      */
22487     DirectionDOMCalculator.prototype.resize = function (element) {
22488         this._resize(element);
22489         this._reset();
22490     };
22491     /**
22492      * Calculates the coordinates on the unit circle for an angle.
22493      *
22494      * @param {number} angle Angle in radians.
22495      * @returns {Array<number>} The x and y coordinates on the unit circle.
22496      */
22497     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
22498         return [Math.cos(angle), Math.sin(angle)];
22499     };
22500     /**
22501      * Calculates the coordinates on the unit circle for the
22502      * relative angle between the first and second angle.
22503      *
22504      * @param {number} first Angle in radians.
22505      * @param {number} second Angle in radians.
22506      * @returns {Array<number>} The x and y coordinates on the unit circle
22507      * for the relative angle between the first and second angle.
22508      */
22509     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
22510         var relativeAngle = this._spatial.wrapAngle(first - second);
22511         return this.angleToCoordinates(relativeAngle);
22512     };
22513     DirectionDOMCalculator.prototype._configure = function (configuration) {
22514         this._minWidth = configuration.minWidth;
22515         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22516     };
22517     DirectionDOMCalculator.prototype._resize = function (element) {
22518         this._elementWidth = element.offsetWidth;
22519         this._elementHeight = element.offsetHeight;
22520     };
22521     DirectionDOMCalculator.prototype._reset = function () {
22522         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22523         this._containerHeight = this._getContainerHeight(this.containerWidth);
22524         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22525         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22526         this._outerRadius = this._getOuterRadius(this._containerHeight);
22527         this._innerRadius = this._getInnerRadius(this._containerHeight);
22528         this._shadowOffset = 3;
22529         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22530         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22531         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22532         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22533         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22534         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22535         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22536         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22537     };
22538     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22539         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22540         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22541         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22542         coeff = 0.04 * Math.round(25 * coeff);
22543         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22544     };
22545     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22546         return 0.77 * containerWidth;
22547     };
22548     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22549         return 0.34 * containerHeight;
22550     };
22551     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22552         return 0.3 * containerHeight;
22553     };
22554     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22555         return 0.31 * containerHeight;
22556     };
22557     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22558         return 0.125 * containerHeight;
22559     };
22560     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22561         return value + "px";
22562     };
22563     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22564         return value > minWidth ? value : minWidth;
22565     };
22566     return DirectionDOMCalculator;
22567 }());
22568 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22569 exports.default = DirectionDOMCalculator;
22570
22571 },{"../../Geo":233}],259:[function(require,module,exports){
22572 "use strict";
22573 /// <reference path="../../../typings/index.d.ts" />
22574 Object.defineProperty(exports, "__esModule", { value: true });
22575 var vd = require("virtual-dom");
22576 var Component_1 = require("../../Component");
22577 var Edge_1 = require("../../Edge");
22578 var Geo_1 = require("../../Geo");
22579 /**
22580  * @class DirectionDOMRenderer
22581  * @classdesc DOM renderer for direction arrows.
22582  */
22583 var DirectionDOMRenderer = (function () {
22584     function DirectionDOMRenderer(configuration, element) {
22585         this._isEdge = false;
22586         this._spatial = new Geo_1.Spatial();
22587         this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
22588         this._node = null;
22589         this._rotation = { phi: 0, theta: 0 };
22590         this._epsilon = 0.5 * Math.PI / 180;
22591         this._highlightKey = null;
22592         this._distinguishSequence = false;
22593         this._needsRender = false;
22594         this._stepEdges = [];
22595         this._turnEdges = [];
22596         this._panoEdges = [];
22597         this._sequenceEdgeKeys = [];
22598         this._stepDirections = [
22599             Edge_1.EdgeDirection.StepForward,
22600             Edge_1.EdgeDirection.StepBackward,
22601             Edge_1.EdgeDirection.StepLeft,
22602             Edge_1.EdgeDirection.StepRight,
22603         ];
22604         this._turnDirections = [
22605             Edge_1.EdgeDirection.TurnLeft,
22606             Edge_1.EdgeDirection.TurnRight,
22607             Edge_1.EdgeDirection.TurnU,
22608         ];
22609         this._turnNames = {};
22610         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22611         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22612         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
22613         // detects IE 8-11, then Edge 20+.
22614         var isIE = !!document.documentMode;
22615         this._isEdge = !isIE && !!window.StyleMedia;
22616     }
22617     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
22618         /**
22619          * Get needs render.
22620          *
22621          * @returns {boolean} Value indicating whether render should be called.
22622          */
22623         get: function () {
22624             return this._needsRender;
22625         },
22626         enumerable: true,
22627         configurable: true
22628     });
22629     /**
22630      * Renders virtual DOM elements.
22631      *
22632      * @description Calling render resets the needs render property.
22633      */
22634     DirectionDOMRenderer.prototype.render = function (navigator) {
22635         this._needsRender = false;
22636         var rotation = this._rotation;
22637         var steps = [];
22638         var turns = [];
22639         if (this._node.pano) {
22640             steps = steps.concat(this._createPanoArrows(navigator, rotation));
22641         }
22642         else {
22643             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
22644             steps = steps.concat(this._createStepArrows(navigator, rotation));
22645             turns = turns.concat(this._createTurnArrows(navigator));
22646         }
22647         return this._getContainer(steps, turns, rotation);
22648     };
22649     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
22650         this._setEdges(edgeStatus, sequence);
22651         this._setNeedsRender();
22652     };
22653     /**
22654      * Set node for which to show edges.
22655      *
22656      * @param {Node} node
22657      */
22658     DirectionDOMRenderer.prototype.setNode = function (node) {
22659         this._node = node;
22660         this._clearEdges();
22661         this._setNeedsRender();
22662     };
22663     /**
22664      * Set the render camera to use for calculating rotations.
22665      *
22666      * @param {RenderCamera} renderCamera
22667      */
22668     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
22669         var rotation = renderCamera.rotation;
22670         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
22671             return;
22672         }
22673         this._rotation = rotation;
22674         this._setNeedsRender();
22675     };
22676     /**
22677      * Set configuration values.
22678      *
22679      * @param {IDirectionConfiguration} configuration
22680      */
22681     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
22682         var needsRender = false;
22683         if (this._highlightKey !== configuration.highlightKey ||
22684             this._distinguishSequence !== configuration.distinguishSequence) {
22685             this._highlightKey = configuration.highlightKey;
22686             this._distinguishSequence = configuration.distinguishSequence;
22687             needsRender = true;
22688         }
22689         if (this._calculator.minWidth !== configuration.minWidth ||
22690             this._calculator.maxWidth !== configuration.maxWidth) {
22691             this._calculator.configure(configuration);
22692             needsRender = true;
22693         }
22694         if (needsRender) {
22695             this._setNeedsRender();
22696         }
22697     };
22698     /**
22699      * Detect the element's width and height and resize
22700      * elements accordingly.
22701      *
22702      * @param {HTMLElement} element Viewer container element.
22703      */
22704     DirectionDOMRenderer.prototype.resize = function (element) {
22705         this._calculator.resize(element);
22706         this._setNeedsRender();
22707     };
22708     DirectionDOMRenderer.prototype._setNeedsRender = function () {
22709         if (this._node != null) {
22710             this._needsRender = true;
22711         }
22712     };
22713     DirectionDOMRenderer.prototype._clearEdges = function () {
22714         this._stepEdges = [];
22715         this._turnEdges = [];
22716         this._panoEdges = [];
22717         this._sequenceEdgeKeys = [];
22718     };
22719     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
22720         this._stepEdges = [];
22721         this._turnEdges = [];
22722         this._panoEdges = [];
22723         this._sequenceEdgeKeys = [];
22724         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22725             var edge = _a[_i];
22726             var direction = edge.data.direction;
22727             if (this._stepDirections.indexOf(direction) > -1) {
22728                 this._stepEdges.push(edge);
22729                 continue;
22730             }
22731             if (this._turnDirections.indexOf(direction) > -1) {
22732                 this._turnEdges.push(edge);
22733                 continue;
22734             }
22735             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
22736                 this._panoEdges.push(edge);
22737             }
22738         }
22739         if (this._distinguishSequence && sequence != null) {
22740             var edges = this._panoEdges
22741                 .concat(this._stepEdges)
22742                 .concat(this._turnEdges);
22743             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
22744                 var edge = edges_1[_b];
22745                 var edgeKey = edge.to;
22746                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22747                     var sequenceKey = _d[_c];
22748                     if (sequenceKey === edgeKey) {
22749                         this._sequenceEdgeKeys.push(edgeKey);
22750                         break;
22751                     }
22752                 }
22753             }
22754         }
22755     };
22756     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
22757         var arrows = [];
22758         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22759             var panoEdge = _a[_i];
22760             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
22761         }
22762         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
22763             var stepEdge = _c[_b];
22764             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22765         }
22766         return arrows;
22767     };
22768     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
22769         var threshold = Math.PI / 8;
22770         var relativePhi = rotation.phi;
22771         switch (direction) {
22772             case Edge_1.EdgeDirection.StepBackward:
22773                 relativePhi = rotation.phi - Math.PI;
22774                 break;
22775             case Edge_1.EdgeDirection.StepLeft:
22776                 relativePhi = rotation.phi + Math.PI / 2;
22777                 break;
22778             case Edge_1.EdgeDirection.StepRight:
22779                 relativePhi = rotation.phi - Math.PI / 2;
22780                 break;
22781             default:
22782                 break;
22783         }
22784         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
22785             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
22786         }
22787         return this._createVNodeDisabled(key, azimuth, rotation);
22788     };
22789     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22790         var arrows = [];
22791         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22792             var panoEdge = _a[_i];
22793             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22794         }
22795         return arrows;
22796     };
22797     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22798         var arrows = [];
22799         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22800             var stepEdge = _a[_i];
22801             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22802         }
22803         return arrows;
22804     };
22805     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22806         var turns = [];
22807         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22808             var turnEdge = _a[_i];
22809             var direction = turnEdge.data.direction;
22810             var name_1 = this._turnNames[direction];
22811             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22812         }
22813         return turns;
22814     };
22815     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22816         var onClick = function (e) {
22817             navigator.moveToKey$(key)
22818                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22819         };
22820         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22821     };
22822     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22823         var onClick = function (e) {
22824             navigator.moveDir$(direction)
22825                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22826         };
22827         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22828     };
22829     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22830         var onClick = function (e) {
22831             navigator.moveDir$(direction)
22832                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22833         };
22834         var style = {
22835             height: this._calculator.turnCircleSizeCss,
22836             transform: "rotate(0)",
22837             width: this._calculator.turnCircleSizeCss,
22838         };
22839         switch (direction) {
22840             case Edge_1.EdgeDirection.TurnLeft:
22841                 style.left = "5px";
22842                 style.top = "5px";
22843                 break;
22844             case Edge_1.EdgeDirection.TurnRight:
22845                 style.right = "5px";
22846                 style.top = "5px";
22847                 break;
22848             case Edge_1.EdgeDirection.TurnU:
22849                 style.left = "5px";
22850                 style.bottom = "5px";
22851                 break;
22852             default:
22853                 break;
22854         }
22855         var circleProperties = {
22856             attributes: {
22857                 "data-key": key,
22858             },
22859             onclick: onClick,
22860             style: style,
22861         };
22862         var circleClassName = "TurnCircle";
22863         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22864             circleClassName += "Sequence";
22865         }
22866         if (this._highlightKey === key) {
22867             circleClassName += "Highlight";
22868         }
22869         var turn = vd.h("div." + className, {}, []);
22870         return vd.h("div." + circleClassName, circleProperties, [turn]);
22871     };
22872     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22873         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22874     };
22875     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22876         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22877         // rotate 90 degrees clockwise and flip over X-axis
22878         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22879         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22880         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22881         var shadowOffset = this._calculator.shadowOffset;
22882         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22883         var shadowTranslationY = shadowOffset * shadowTranslation[0];
22884         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22885         var properties = {
22886             style: {
22887                 "-webkit-filter": filter,
22888                 filter: filter,
22889             },
22890         };
22891         var chevron = vd.h("div." + className, properties, []);
22892         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22893         var circleTransform = shiftVertically ?
22894             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22895             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22896         var circleProperties = {
22897             attributes: { "data-key": key },
22898             onclick: onClick,
22899             style: {
22900                 height: this._calculator.stepCircleSizeCss,
22901                 marginLeft: this._calculator.stepCircleMarginCss,
22902                 marginTop: this._calculator.stepCircleMarginCss,
22903                 transform: circleTransform,
22904                 width: this._calculator.stepCircleSizeCss,
22905             },
22906         };
22907         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22908             circleClassName += "Sequence";
22909         }
22910         if (this._highlightKey === key) {
22911             circleClassName += "Highlight";
22912         }
22913         return vd.h("div." + circleClassName, circleProperties, [chevron]);
22914     };
22915     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22916         // edge does not handle hover on perspective transforms.
22917         var transform = this._isEdge ?
22918             "rotateX(60deg)" :
22919             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22920         var properties = {
22921             oncontextmenu: function (event) { event.preventDefault(); },
22922             style: {
22923                 bottom: this._calculator.containerBottomCss,
22924                 height: this._calculator.containerHeightCss,
22925                 left: this._calculator.containerLeftCss,
22926                 marginLeft: this._calculator.containerMarginCss,
22927                 transform: transform,
22928                 width: this._calculator.containerWidthCss,
22929             },
22930         };
22931         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22932     };
22933     return DirectionDOMRenderer;
22934 }());
22935 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22936 exports.default = DirectionDOMRenderer;
22937
22938 },{"../../Component":230,"../../Edge":231,"../../Geo":233,"virtual-dom":186}],260:[function(require,module,exports){
22939 "use strict";
22940 var __extends = (this && this.__extends) || (function () {
22941     var extendStatics = Object.setPrototypeOf ||
22942         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22943         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22944     return function (d, b) {
22945         extendStatics(d, b);
22946         function __() { this.constructor = d; }
22947         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22948     };
22949 })();
22950 Object.defineProperty(exports, "__esModule", { value: true });
22951 var Observable_1 = require("rxjs/Observable");
22952 var Subject_1 = require("rxjs/Subject");
22953 require("rxjs/add/operator/catch");
22954 require("rxjs/add/operator/combineLatest");
22955 require("rxjs/add/operator/debounceTime");
22956 require("rxjs/add/operator/distinctUntilChanged");
22957 require("rxjs/add/operator/filter");
22958 require("rxjs/add/operator/map");
22959 require("rxjs/add/operator/pairwise");
22960 require("rxjs/add/operator/publish");
22961 require("rxjs/add/operator/publishReplay");
22962 require("rxjs/add/operator/scan");
22963 require("rxjs/add/operator/skipWhile");
22964 require("rxjs/add/operator/startWith");
22965 require("rxjs/add/operator/switchMap");
22966 require("rxjs/add/operator/takeUntil");
22967 require("rxjs/add/operator/withLatestFrom");
22968 var Component_1 = require("../../Component");
22969 var Render_1 = require("../../Render");
22970 var Tiles_1 = require("../../Tiles");
22971 var Utils_1 = require("../../Utils");
22972 var ImagePlaneComponent = (function (_super) {
22973     __extends(ImagePlaneComponent, _super);
22974     function ImagePlaneComponent(name, container, navigator) {
22975         var _this = _super.call(this, name, container, navigator) || this;
22976         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22977         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22978         _this._rendererOperation$ = new Subject_1.Subject();
22979         _this._rendererCreator$ = new Subject_1.Subject();
22980         _this._rendererDisposer$ = new Subject_1.Subject();
22981         _this._renderer$ = _this._rendererOperation$
22982             .scan(function (renderer, operation) {
22983             return operation(renderer);
22984         }, null)
22985             .filter(function (renderer) {
22986             return renderer != null;
22987         })
22988             .distinctUntilChanged(undefined, function (renderer) {
22989             return renderer.frameId;
22990         });
22991         _this._rendererCreator$
22992             .map(function () {
22993             return function (renderer) {
22994                 if (renderer != null) {
22995                     throw new Error("Multiple image plane states can not be created at the same time");
22996                 }
22997                 return new Component_1.ImagePlaneGLRenderer();
22998             };
22999         })
23000             .subscribe(_this._rendererOperation$);
23001         _this._rendererDisposer$
23002             .map(function () {
23003             return function (renderer) {
23004                 renderer.dispose();
23005                 return null;
23006             };
23007         })
23008             .subscribe(_this._rendererOperation$);
23009         return _this;
23010     }
23011     ImagePlaneComponent.prototype._activate = function () {
23012         var _this = this;
23013         this._rendererSubscription = this._renderer$
23014             .map(function (renderer) {
23015             var renderHash = {
23016                 name: _this._name,
23017                 render: {
23018                     frameId: renderer.frameId,
23019                     needsRender: renderer.needsRender,
23020                     render: renderer.render.bind(renderer),
23021                     stage: Render_1.GLRenderStage.Background,
23022                 },
23023             };
23024             renderer.clearNeedsRender();
23025             return renderHash;
23026         })
23027             .subscribe(this._container.glRenderer.render$);
23028         this._rendererCreator$.next(null);
23029         this._stateSubscription = this._navigator.stateService.currentState$
23030             .map(function (frame) {
23031             return function (renderer) {
23032                 renderer.updateFrame(frame);
23033                 return renderer;
23034             };
23035         })
23036             .subscribe(this._rendererOperation$);
23037         var textureProvider$ = this._navigator.stateService.currentState$
23038             .distinctUntilChanged(undefined, function (frame) {
23039             return frame.state.currentNode.key;
23040         })
23041             .combineLatest(this._configuration$)
23042             .filter(function (args) {
23043             return args[1].imageTiling === true;
23044         })
23045             .map(function (args) {
23046             return args[0];
23047         })
23048             .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
23049             .map(function (_a) {
23050             var frame = _a[0], renderer = _a[1], size = _a[2];
23051             var state = frame.state;
23052             var viewportSize = Math.max(size.width, size.height);
23053             var currentNode = state.currentNode;
23054             var currentTransform = state.currentTransform;
23055             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
23056             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
23057         })
23058             .publishReplay(1)
23059             .refCount();
23060         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
23061         this._setTextureProviderSubscription = textureProvider$
23062             .map(function (provider) {
23063             return function (renderer) {
23064                 renderer.setTextureProvider(provider.key, provider);
23065                 return renderer;
23066             };
23067         })
23068             .subscribe(this._rendererOperation$);
23069         this._setTileSizeSubscription = this._container.renderService.size$
23070             .switchMap(function (size) {
23071             return Observable_1.Observable
23072                 .combineLatest(textureProvider$, Observable_1.Observable.of(size))
23073                 .first();
23074         })
23075             .subscribe(function (_a) {
23076             var provider = _a[0], size = _a[1];
23077             var viewportSize = Math.max(size.width, size.height);
23078             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
23079             provider.setTileSize(tileSize);
23080         });
23081         this._abortTextureProviderSubscription = textureProvider$
23082             .pairwise()
23083             .subscribe(function (pair) {
23084             var previous = pair[0];
23085             previous.abort();
23086         });
23087         var roiTrigger$ = Observable_1.Observable
23088             .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
23089             .map(function (_a) {
23090             var camera = _a[0], size = _a[1];
23091             return [
23092                 camera.camera.position.clone(),
23093                 camera.camera.lookat.clone(),
23094                 camera.zoom.valueOf(),
23095                 size.height.valueOf(),
23096                 size.width.valueOf()
23097             ];
23098         })
23099             .pairwise()
23100             .skipWhile(function (pls) {
23101             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
23102         })
23103             .map(function (pls) {
23104             var samePosition = pls[0][0].equals(pls[1][0]);
23105             var sameLookat = pls[0][1].equals(pls[1][1]);
23106             var sameZoom = pls[0][2] === pls[1][2];
23107             var sameHeight = pls[0][3] === pls[1][3];
23108             var sameWidth = pls[0][4] === pls[1][4];
23109             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
23110         })
23111             .distinctUntilChanged()
23112             .filter(function (stalled) {
23113             return stalled;
23114         })
23115             .switchMap(function (stalled) {
23116             return _this._container.renderService.renderCameraFrame$
23117                 .first();
23118         })
23119             .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
23120         this._setRegionOfInterestSubscription = textureProvider$
23121             .switchMap(function (provider) {
23122             return roiTrigger$
23123                 .map(function (_a) {
23124                 var camera = _a[0], size = _a[1], transform = _a[2];
23125                 return [
23126                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
23127                     provider,
23128                 ];
23129             });
23130         })
23131             .filter(function (args) {
23132             return !args[1].disposed;
23133         })
23134             .subscribe(function (args) {
23135             var roi = args[0];
23136             var provider = args[1];
23137             provider.setRegionOfInterest(roi);
23138         });
23139         var hasTexture$ = textureProvider$
23140             .switchMap(function (provider) {
23141             return provider.hasTexture$;
23142         })
23143             .startWith(false)
23144             .publishReplay(1)
23145             .refCount();
23146         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
23147         var nodeImage$ = this._navigator.stateService.currentNode$
23148             .debounceTime(1000)
23149             .withLatestFrom(hasTexture$)
23150             .filter(function (args) {
23151             return !args[1];
23152         })
23153             .map(function (args) {
23154             return args[0];
23155         })
23156             .filter(function (node) {
23157             return node.pano ?
23158                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23159                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23160         })
23161             .switchMap(function (node) {
23162             var baseImageSize = node.pano ?
23163                 Utils_1.Settings.basePanoramaSize :
23164                 Utils_1.Settings.baseImageSize;
23165             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23166                 return Observable_1.Observable.empty();
23167             }
23168             var image$ = node
23169                 .cacheImage$(Utils_1.Settings.maxImageSize)
23170                 .map(function (n) {
23171                 return [n.image, n];
23172             });
23173             return image$
23174                 .takeUntil(hasTexture$
23175                 .filter(function (hasTexture) {
23176                 return hasTexture;
23177             }))
23178                 .catch(function (error, caught) {
23179                 console.error("Failed to fetch high res image (" + node.key + ")", error);
23180                 return Observable_1.Observable.empty();
23181             });
23182         })
23183             .publish()
23184             .refCount();
23185         this._updateBackgroundSubscription = nodeImage$
23186             .withLatestFrom(textureProvider$)
23187             .subscribe(function (args) {
23188             if (args[0][1].key !== args[1].key ||
23189                 args[1].disposed) {
23190                 return;
23191             }
23192             args[1].updateBackground(args[0][0]);
23193         });
23194         this._updateTextureImageSubscription = nodeImage$
23195             .map(function (imn) {
23196             return function (renderer) {
23197                 renderer.updateTextureImage(imn[0], imn[1]);
23198                 return renderer;
23199             };
23200         })
23201             .subscribe(this._rendererOperation$);
23202     };
23203     ImagePlaneComponent.prototype._deactivate = function () {
23204         this._rendererDisposer$.next(null);
23205         this._abortTextureProviderSubscription.unsubscribe();
23206         this._hasTextureSubscription.unsubscribe();
23207         this._rendererSubscription.unsubscribe();
23208         this._setRegionOfInterestSubscription.unsubscribe();
23209         this._setTextureProviderSubscription.unsubscribe();
23210         this._setTileSizeSubscription.unsubscribe();
23211         this._stateSubscription.unsubscribe();
23212         this._textureProviderSubscription.unsubscribe();
23213         this._updateBackgroundSubscription.unsubscribe();
23214         this._updateTextureImageSubscription.unsubscribe();
23215     };
23216     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
23217         return { imageTiling: false };
23218     };
23219     ImagePlaneComponent.componentName = "imagePlane";
23220     return ImagePlaneComponent;
23221 }(Component_1.Component));
23222 exports.ImagePlaneComponent = ImagePlaneComponent;
23223 Component_1.ComponentService.register(ImagePlaneComponent);
23224 exports.default = ImagePlaneComponent;
23225
23226 },{"../../Component":230,"../../Render":236,"../../Tiles":239,"../../Utils":240,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publish":71,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/skipWhile":78,"rxjs/add/operator/startWith":79,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/takeUntil":82,"rxjs/add/operator/withLatestFrom":85}],261:[function(require,module,exports){
23227 "use strict";
23228 /// <reference path="../../../typings/index.d.ts" />
23229 Object.defineProperty(exports, "__esModule", { value: true });
23230 var THREE = require("three");
23231 var Component_1 = require("../../Component");
23232 var ImagePlaneFactory = (function () {
23233     function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
23234         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
23235         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
23236     }
23237     ImagePlaneFactory.prototype.createMesh = function (node, transform) {
23238         var mesh = node.pano ?
23239             this._createImageSphere(node, transform) :
23240             this._createImagePlane(node, transform);
23241         return mesh;
23242     };
23243     ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
23244         var texture = this._createTexture(node.image);
23245         var materialParameters = this._createSphereMaterialParameters(transform, texture);
23246         var material = new THREE.ShaderMaterial(materialParameters);
23247         var mesh = this._useMesh(transform, node) ?
23248             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
23249             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
23250         return mesh;
23251     };
23252     ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
23253         var texture = this._createTexture(node.image);
23254         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
23255         var material = new THREE.ShaderMaterial(materialParameters);
23256         var geometry = this._useMesh(transform, node) ?
23257             this._getImagePlaneGeo(transform, node) :
23258             this._getFlatImagePlaneGeo(transform);
23259         return new THREE.Mesh(geometry, material);
23260     };
23261     ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
23262         var gpano = transform.gpano;
23263         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
23264         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
23265         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23266         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
23267         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
23268         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23269         var materialParameters = {
23270             depthWrite: false,
23271             fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
23272             side: THREE.DoubleSide,
23273             transparent: true,
23274             uniforms: {
23275                 opacity: {
23276                     type: "f",
23277                     value: 1,
23278                 },
23279                 phiLength: {
23280                     type: "f",
23281                     value: phiLength,
23282                 },
23283                 phiShift: {
23284                     type: "f",
23285                     value: phiShift,
23286                 },
23287                 projectorMat: {
23288                     type: "m4",
23289                     value: transform.rt,
23290                 },
23291                 projectorTex: {
23292                     type: "t",
23293                     value: texture,
23294                 },
23295                 thetaLength: {
23296                     type: "f",
23297                     value: thetaLength,
23298                 },
23299                 thetaShift: {
23300                     type: "f",
23301                     value: thetaShift,
23302                 },
23303             },
23304             vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
23305         };
23306         return materialParameters;
23307     };
23308     ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
23309         var materialParameters = {
23310             depthWrite: false,
23311             fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
23312             side: THREE.DoubleSide,
23313             transparent: true,
23314             uniforms: {
23315                 bbox: {
23316                     type: "v4",
23317                     value: new THREE.Vector4(0, 0, 1, 1),
23318                 },
23319                 opacity: {
23320                     type: "f",
23321                     value: 1,
23322                 },
23323                 projectorMat: {
23324                     type: "m4",
23325                     value: transform.projectorMatrix(),
23326                 },
23327                 projectorTex: {
23328                     type: "t",
23329                     value: texture,
23330                 },
23331             },
23332             vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
23333         };
23334         return materialParameters;
23335     };
23336     ImagePlaneFactory.prototype._createTexture = function (image) {
23337         var texture = new THREE.Texture(image);
23338         texture.minFilter = THREE.LinearFilter;
23339         texture.needsUpdate = true;
23340         return texture;
23341     };
23342     ImagePlaneFactory.prototype._useMesh = function (transform, node) {
23343         return node.mesh.vertices.length && transform.hasValidScale;
23344     };
23345     ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
23346         var t = new THREE.Matrix4().getInverse(transform.srt);
23347         // push everything at least 5 meters in front of the camera
23348         var minZ = 5.0 * transform.scale;
23349         var maxZ = this._imageSphereRadius * transform.scale;
23350         var vertices = node.mesh.vertices;
23351         var numVertices = vertices.length / 3;
23352         var positions = new Float32Array(vertices.length);
23353         for (var i = 0; i < numVertices; ++i) {
23354             var index = 3 * i;
23355             var x = vertices[index + 0];
23356             var y = vertices[index + 1];
23357             var z = vertices[index + 2];
23358             var l = Math.sqrt(x * x + y * y + z * z);
23359             var boundedL = Math.max(minZ, Math.min(l, maxZ));
23360             var factor = boundedL / l;
23361             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
23362             p.applyMatrix4(t);
23363             positions[index + 0] = p.x;
23364             positions[index + 1] = p.y;
23365             positions[index + 2] = p.z;
23366         }
23367         var faces = node.mesh.faces;
23368         var indices = new Uint16Array(faces.length);
23369         for (var i = 0; i < faces.length; ++i) {
23370             indices[i] = faces[i];
23371         }
23372         var geometry = new THREE.BufferGeometry();
23373         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23374         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23375         return geometry;
23376     };
23377     ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
23378         var t = new THREE.Matrix4().getInverse(transform.srt);
23379         // push everything at least 5 meters in front of the camera
23380         var minZ = 5.0 * transform.scale;
23381         var maxZ = this._imagePlaneDepth * transform.scale;
23382         var vertices = node.mesh.vertices;
23383         var numVertices = vertices.length / 3;
23384         var positions = new Float32Array(vertices.length);
23385         for (var i = 0; i < numVertices; ++i) {
23386             var index = 3 * i;
23387             var x = vertices[index + 0];
23388             var y = vertices[index + 1];
23389             var z = vertices[index + 2];
23390             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
23391             var factor = boundedZ / z;
23392             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
23393             p.applyMatrix4(t);
23394             positions[index + 0] = p.x;
23395             positions[index + 1] = p.y;
23396             positions[index + 2] = p.z;
23397         }
23398         var faces = node.mesh.faces;
23399         var indices = new Uint16Array(faces.length);
23400         for (var i = 0; i < faces.length; ++i) {
23401             indices[i] = faces[i];
23402         }
23403         var geometry = new THREE.BufferGeometry();
23404         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23405         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23406         return geometry;
23407     };
23408     ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
23409         var gpano = transform.gpano;
23410         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
23411         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23412         var thetaStart = Math.PI *
23413             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
23414             gpano.FullPanoHeightPixels;
23415         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23416         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
23417         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
23418         return geometry;
23419     };
23420     ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
23421         var width = transform.width;
23422         var height = transform.height;
23423         var size = Math.max(width, height);
23424         var dx = width / 2.0 / size;
23425         var dy = height / 2.0 / size;
23426         var vertices = [];
23427         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
23428         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
23429         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
23430         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
23431         var positions = new Float32Array(12);
23432         for (var i = 0; i < vertices.length; i++) {
23433             var index = 3 * i;
23434             positions[index + 0] = vertices[i][0];
23435             positions[index + 1] = vertices[i][1];
23436             positions[index + 2] = vertices[i][2];
23437         }
23438         var indices = new Uint16Array(6);
23439         indices[0] = 0;
23440         indices[1] = 1;
23441         indices[2] = 3;
23442         indices[3] = 1;
23443         indices[4] = 2;
23444         indices[5] = 3;
23445         var geometry = new THREE.BufferGeometry();
23446         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23447         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23448         return geometry;
23449     };
23450     return ImagePlaneFactory;
23451 }());
23452 exports.ImagePlaneFactory = ImagePlaneFactory;
23453 exports.default = ImagePlaneFactory;
23454
23455 },{"../../Component":230,"three":180}],262:[function(require,module,exports){
23456 "use strict";
23457 /// <reference path="../../../typings/index.d.ts" />
23458 Object.defineProperty(exports, "__esModule", { value: true });
23459 var Component_1 = require("../../Component");
23460 var Geo_1 = require("../../Geo");
23461 var ImagePlaneGLRenderer = (function () {
23462     function ImagePlaneGLRenderer() {
23463         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23464         this._imagePlaneScene = new Component_1.ImagePlaneScene();
23465         this._alpha = 0;
23466         this._alphaOld = 0;
23467         this._fadeOutSpeed = 0.05;
23468         this._lastCamera = new Geo_1.Camera();
23469         this._epsilon = 0.000001;
23470         this._currentKey = null;
23471         this._previousKey = null;
23472         this._providerDisposers = {};
23473         this._frameId = 0;
23474         this._needsRender = false;
23475     }
23476     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
23477         get: function () {
23478             return this._frameId;
23479         },
23480         enumerable: true,
23481         configurable: true
23482     });
23483     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
23484         get: function () {
23485             return this._needsRender;
23486         },
23487         enumerable: true,
23488         configurable: true
23489     });
23490     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
23491         this._needsRender = true;
23492     };
23493     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
23494         this._updateFrameId(frame.id);
23495         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
23496         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
23497         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
23498     };
23499     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
23500         var _this = this;
23501         if (key !== this._currentKey) {
23502             return;
23503         }
23504         var createdSubscription = provider.textureCreated$
23505             .subscribe(function (texture) {
23506             _this._updateTexture(texture);
23507         });
23508         var updatedSubscription = provider.textureUpdated$
23509             .subscribe(function (updated) {
23510             _this._needsRender = true;
23511         });
23512         var dispose = function () {
23513             createdSubscription.unsubscribe();
23514             updatedSubscription.unsubscribe();
23515             provider.dispose();
23516         };
23517         if (key in this._providerDisposers) {
23518             var disposeProvider = this._providerDisposers[key];
23519             disposeProvider();
23520             delete this._providerDisposers[key];
23521         }
23522         this._providerDisposers[key] = dispose;
23523     };
23524     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
23525         this._needsRender = true;
23526         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23527             var plane = _a[_i];
23528             var material = plane.material;
23529             var oldTexture = material.uniforms.projectorTex.value;
23530             material.uniforms.projectorTex.value = null;
23531             oldTexture.dispose();
23532             material.uniforms.projectorTex.value = texture;
23533         }
23534     };
23535     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
23536         if (this._currentKey !== node.key) {
23537             return;
23538         }
23539         this._needsRender = true;
23540         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23541             var plane = _a[_i];
23542             var material = plane.material;
23543             var texture = material.uniforms.projectorTex.value;
23544             texture.image = image;
23545             texture.needsUpdate = true;
23546         }
23547     };
23548     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23549         var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
23550         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23551             var plane = _a[_i];
23552             plane.material.uniforms.opacity.value = planeAlpha;
23553         }
23554         for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
23555             var plane = _c[_b];
23556             plane.material.uniforms.opacity.value = this._alphaOld;
23557         }
23558         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23559         renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23560         for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
23561             var plane = _e[_d];
23562             plane.material.uniforms.opacity.value = this._alpha;
23563         }
23564         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23565     };
23566     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23567         this._needsRender = false;
23568     };
23569     ImagePlaneGLRenderer.prototype.dispose = function () {
23570         this._imagePlaneScene.clear();
23571     };
23572     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23573         this._frameId = frameId;
23574     };
23575     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23576         if (alpha === this._alpha) {
23577             return false;
23578         }
23579         this._alpha = alpha;
23580         return true;
23581     };
23582     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23583         if (alpha < 1 || this._alphaOld === 0) {
23584             return false;
23585         }
23586         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23587         return true;
23588     };
23589     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23590         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23591             return false;
23592         }
23593         var previousKey = state.previousNode != null ? state.previousNode.key : null;
23594         var currentKey = state.currentNode.key;
23595         if (this._previousKey !== previousKey &&
23596             this._previousKey !== currentKey &&
23597             this._previousKey in this._providerDisposers) {
23598             var disposeProvider = this._providerDisposers[this._previousKey];
23599             disposeProvider();
23600             delete this._providerDisposers[this._previousKey];
23601         }
23602         if (previousKey != null) {
23603             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23604                 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
23605                 this._imagePlaneScene.updateImagePlanes([previousMesh]);
23606             }
23607             this._previousKey = previousKey;
23608         }
23609         this._currentKey = currentKey;
23610         var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
23611         this._imagePlaneScene.updateImagePlanes([currentMesh]);
23612         this._alphaOld = 1;
23613         return true;
23614     };
23615     return ImagePlaneGLRenderer;
23616 }());
23617 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23618 exports.default = ImagePlaneGLRenderer;
23619
23620 },{"../../Component":230,"../../Geo":233}],263:[function(require,module,exports){
23621 "use strict";
23622 /// <reference path="../../../typings/index.d.ts" />
23623 Object.defineProperty(exports, "__esModule", { value: true });
23624 var THREE = require("three");
23625 var ImagePlaneScene = (function () {
23626     function ImagePlaneScene() {
23627         this.scene = new THREE.Scene();
23628         this.sceneOld = new THREE.Scene();
23629         this.imagePlanes = [];
23630         this.imagePlanesOld = [];
23631     }
23632     ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
23633         this._dispose(this.imagePlanesOld, this.sceneOld);
23634         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
23635             var plane = _a[_i];
23636             this.scene.remove(plane);
23637             this.sceneOld.add(plane);
23638         }
23639         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
23640             var plane = planes_1[_b];
23641             this.scene.add(plane);
23642         }
23643         this.imagePlanesOld = this.imagePlanes;
23644         this.imagePlanes = planes;
23645     };
23646     ImagePlaneScene.prototype.addImagePlanes = function (planes) {
23647         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
23648             var plane = planes_2[_i];
23649             this.scene.add(plane);
23650             this.imagePlanes.push(plane);
23651         }
23652     };
23653     ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
23654         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
23655             var plane = planes_3[_i];
23656             this.sceneOld.add(plane);
23657             this.imagePlanesOld.push(plane);
23658         }
23659     };
23660     ImagePlaneScene.prototype.setImagePlanes = function (planes) {
23661         this._clear();
23662         this.addImagePlanes(planes);
23663     };
23664     ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
23665         this._clearOld();
23666         this.addImagePlanesOld(planes);
23667     };
23668     ImagePlaneScene.prototype.clear = function () {
23669         this._clear();
23670         this._clearOld();
23671     };
23672     ImagePlaneScene.prototype._clear = function () {
23673         this._dispose(this.imagePlanes, this.scene);
23674         this.imagePlanes.length = 0;
23675     };
23676     ImagePlaneScene.prototype._clearOld = function () {
23677         this._dispose(this.imagePlanesOld, this.sceneOld);
23678         this.imagePlanesOld.length = 0;
23679     };
23680     ImagePlaneScene.prototype._dispose = function (planes, scene) {
23681         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
23682             var plane = planes_4[_i];
23683             scene.remove(plane);
23684             plane.geometry.dispose();
23685             plane.material.dispose();
23686             var texture = plane.material.uniforms.projectorTex.value;
23687             if (texture != null) {
23688                 texture.dispose();
23689             }
23690         }
23691     };
23692     return ImagePlaneScene;
23693 }());
23694 exports.ImagePlaneScene = ImagePlaneScene;
23695 exports.default = ImagePlaneScene;
23696
23697 },{"three":180}],264:[function(require,module,exports){
23698 "use strict";
23699 /// <reference path="../../../typings/index.d.ts" />
23700 Object.defineProperty(exports, "__esModule", { value: true });
23701
23702 var path = require("path");
23703 var ImagePlaneShaders = (function () {
23704     function ImagePlaneShaders() {
23705     }
23706     ImagePlaneShaders.equirectangular = {
23707         fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    vec3 b = normalize(vRstq.xyz);\n    float lat = -asin(b.y);\n    float lon = atan(b.x, b.z);\n    float x = (lon - phiShift) / phiLength + 0.5;\n    float y = (lat - thetaShift) / thetaLength + 0.5;\n    vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n    baseColor.a = opacity;\n    gl_FragColor = baseColor;\n}",
23708         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}",
23709     };
23710     ImagePlaneShaders.perspective = {
23711         fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.w;\n    float y = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if (x > bbox[0] && y > bbox[1] && x < bbox[2] && y < bbox[3]) {\n        baseColor = texture2D(projectorTex, vec2(x, y));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}",
23712         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}",
23713     };
23714     return ImagePlaneShaders;
23715 }());
23716 exports.ImagePlaneShaders = ImagePlaneShaders;
23717
23718 },{"path":22}],265:[function(require,module,exports){
23719 "use strict";
23720 /// <reference path="../../../typings/index.d.ts" />
23721 var __extends = (this && this.__extends) || (function () {
23722     var extendStatics = Object.setPrototypeOf ||
23723         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23724         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23725     return function (d, b) {
23726         extendStatics(d, b);
23727         function __() { this.constructor = d; }
23728         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23729     };
23730 })();
23731 Object.defineProperty(exports, "__esModule", { value: true });
23732 var Observable_1 = require("rxjs/Observable");
23733 var Subject_1 = require("rxjs/Subject");
23734 require("rxjs/add/observable/combineLatest");
23735 require("rxjs/add/observable/fromEvent");
23736 require("rxjs/add/observable/of");
23737 require("rxjs/add/observable/zip");
23738 require("rxjs/add/operator/distinctUntilChanged");
23739 require("rxjs/add/operator/filter");
23740 require("rxjs/add/operator/first");
23741 require("rxjs/add/operator/map");
23742 require("rxjs/add/operator/merge");
23743 require("rxjs/add/operator/mergeMap");
23744 require("rxjs/add/operator/scan");
23745 require("rxjs/add/operator/switchMap");
23746 require("rxjs/add/operator/withLatestFrom");
23747 require("rxjs/add/operator/zip");
23748 var State_1 = require("../../State");
23749 var Render_1 = require("../../Render");
23750 var Utils_1 = require("../../Utils");
23751 var Component_1 = require("../../Component");
23752 var SliderState = (function () {
23753     function SliderState() {
23754         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23755         this._imagePlaneScene = new Component_1.ImagePlaneScene();
23756         this._currentKey = null;
23757         this._previousKey = null;
23758         this._currentPano = false;
23759         this._frameId = 0;
23760         this._glNeedsRender = false;
23761         this._domNeedsRender = true;
23762         this._curtain = 1;
23763     }
23764     Object.defineProperty(SliderState.prototype, "frameId", {
23765         get: function () {
23766             return this._frameId;
23767         },
23768         enumerable: true,
23769         configurable: true
23770     });
23771     Object.defineProperty(SliderState.prototype, "curtain", {
23772         get: function () {
23773             return this._curtain;
23774         },
23775         enumerable: true,
23776         configurable: true
23777     });
23778     Object.defineProperty(SliderState.prototype, "glNeedsRender", {
23779         get: function () {
23780             return this._glNeedsRender;
23781         },
23782         enumerable: true,
23783         configurable: true
23784     });
23785     Object.defineProperty(SliderState.prototype, "domNeedsRender", {
23786         get: function () {
23787             return this._domNeedsRender;
23788         },
23789         enumerable: true,
23790         configurable: true
23791     });
23792     Object.defineProperty(SliderState.prototype, "sliderVisible", {
23793         get: function () {
23794             return this._sliderVisible;
23795         },
23796         set: function (value) {
23797             this._sliderVisible = value;
23798             this._domNeedsRender = true;
23799         },
23800         enumerable: true,
23801         configurable: true
23802     });
23803     Object.defineProperty(SliderState.prototype, "disabled", {
23804         get: function () {
23805             return this._currentKey == null ||
23806                 this._previousKey == null ||
23807                 this._currentPano;
23808         },
23809         enumerable: true,
23810         configurable: true
23811     });
23812     SliderState.prototype.update = function (frame) {
23813         this._updateFrameId(frame.id);
23814         var needsRender = this._updateImagePlanes(frame.state);
23815         this._domNeedsRender = needsRender || this._domNeedsRender;
23816         needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
23817         this._glNeedsRender = needsRender || this._glNeedsRender;
23818     };
23819     SliderState.prototype.updateTexture = function (image, node) {
23820         var imagePlanes = node.key === this._currentKey ?
23821             this._imagePlaneScene.imagePlanes :
23822             node.key === this._previousKey ?
23823                 this._imagePlaneScene.imagePlanesOld :
23824                 [];
23825         if (imagePlanes.length === 0) {
23826             return;
23827         }
23828         this._glNeedsRender = true;
23829         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23830             var plane = imagePlanes_1[_i];
23831             var material = plane.material;
23832             var texture = material.uniforms.projectorTex.value;
23833             texture.image = image;
23834             texture.needsUpdate = true;
23835         }
23836     };
23837     SliderState.prototype.render = function (perspectiveCamera, renderer) {
23838         if (!this.disabled) {
23839             renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23840         }
23841         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23842     };
23843     SliderState.prototype.dispose = function () {
23844         this._imagePlaneScene.clear();
23845     };
23846     SliderState.prototype.clearGLNeedsRender = function () {
23847         this._glNeedsRender = false;
23848     };
23849     SliderState.prototype.clearDomNeedsRender = function () {
23850         this._domNeedsRender = false;
23851     };
23852     SliderState.prototype._updateFrameId = function (frameId) {
23853         this._frameId = frameId;
23854     };
23855     SliderState.prototype._updateImagePlanes = function (state) {
23856         if (state.currentNode == null) {
23857             return;
23858         }
23859         var needsRender = false;
23860         if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23861             needsRender = true;
23862             this._previousKey = state.previousNode.key;
23863             this._imagePlaneScene.setImagePlanesOld([
23864                 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23865             ]);
23866         }
23867         if (this._currentKey !== state.currentNode.key) {
23868             needsRender = true;
23869             this._currentKey = state.currentNode.key;
23870             this._currentPano = state.currentNode.pano;
23871             this._imagePlaneScene.setImagePlanes([
23872                 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23873             ]);
23874             if (!this.disabled) {
23875                 this._updateBbox();
23876             }
23877         }
23878         return needsRender;
23879     };
23880     SliderState.prototype._updateCurtain = function (alpha) {
23881         if (this.disabled ||
23882             Math.abs(this._curtain - alpha) < 0.001) {
23883             return false;
23884         }
23885         this._curtain = alpha;
23886         this._updateBbox();
23887         return true;
23888     };
23889     SliderState.prototype._updateBbox = function () {
23890         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23891             var plane = _a[_i];
23892             var shaderMaterial = plane.material;
23893             var bbox = shaderMaterial.uniforms.bbox.value;
23894             bbox.z = this._curtain;
23895         }
23896     };
23897     return SliderState;
23898 }());
23899 var SliderComponent = (function (_super) {
23900     __extends(SliderComponent, _super);
23901     /**
23902      * Create a new slider component instance.
23903      * @class SliderComponent
23904      */
23905     function SliderComponent(name, container, navigator, dom) {
23906         var _this = _super.call(this, name, container, navigator) || this;
23907         _this._dom = !!dom ? dom : new Utils_1.DOM();
23908         _this._sliderStateOperation$ = new Subject_1.Subject();
23909         _this._sliderStateCreator$ = new Subject_1.Subject();
23910         _this._sliderStateDisposer$ = new Subject_1.Subject();
23911         _this._sliderState$ = _this._sliderStateOperation$
23912             .scan(function (sliderState, operation) {
23913             return operation(sliderState);
23914         }, null)
23915             .filter(function (sliderState) {
23916             return sliderState != null;
23917         })
23918             .distinctUntilChanged(undefined, function (sliderState) {
23919             return sliderState.frameId;
23920         });
23921         _this._sliderStateCreator$
23922             .map(function () {
23923             return function (sliderState) {
23924                 if (sliderState != null) {
23925                     throw new Error("Multiple slider states can not be created at the same time");
23926                 }
23927                 return new SliderState();
23928             };
23929         })
23930             .subscribe(_this._sliderStateOperation$);
23931         _this._sliderStateDisposer$
23932             .map(function () {
23933             return function (sliderState) {
23934                 sliderState.dispose();
23935                 return null;
23936             };
23937         })
23938             .subscribe(_this._sliderStateOperation$);
23939         return _this;
23940     }
23941     /**
23942      * Set the image keys.
23943      *
23944      * Configures the component to show the image planes for the supplied image keys.
23945      *
23946      * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23947      */
23948     SliderComponent.prototype.setKeys = function (keys) {
23949         this.configure({ keys: keys });
23950     };
23951     /**
23952      * Set the initial position.
23953      *
23954      * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23955      *
23956      * @param {number} initialPosition - Initial slider position.
23957      */
23958     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23959         this.configure({ initialPosition: initialPosition });
23960     };
23961     /**
23962      * Set the value controlling if the slider is visible.
23963      *
23964      * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23965      */
23966     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23967         this.configure({ sliderVisible: sliderVisible });
23968     };
23969     SliderComponent.prototype._activate = function () {
23970         var _this = this;
23971         this._sliderContainer = this._dom.createElement("div", "mapillary-js-slider-container", this._container.element);
23972         this._sliderWrapper = this._dom.createElement("div", "SliderWrapper", this._sliderContainer);
23973         this._sliderControl = this._dom.createElement("input", "SliderControl", this._sliderWrapper);
23974         this._sliderControl.setAttribute("type", "range");
23975         this._sliderControl.setAttribute("min", "0");
23976         this._sliderControl.setAttribute("max", "1000");
23977         this._sliderControl.style.visibility = "hidden";
23978         this._moveToHandler = function (e) {
23979             var curtain = Number(e.target.value) / 1000;
23980             _this._navigator.stateService.moveTo(curtain);
23981         };
23982         this._sliderControl.addEventListener("input", this._moveToHandler);
23983         this._sliderControl.addEventListener("change", this._moveToHandler);
23984         Observable_1.Observable
23985             .combineLatest(this._navigator.stateService.state$, this._configuration$)
23986             .first()
23987             .subscribe(function (_a) {
23988             var state = _a[0], configuration = _a[1];
23989             if (state === State_1.State.Traversing) {
23990                 _this._navigator.stateService.wait();
23991                 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
23992                 _this._sliderControl.value = (1000 * position).toString();
23993                 _this._navigator.stateService.moveTo(position);
23994             }
23995         });
23996         this._glRenderSubscription = this._sliderState$
23997             .map(function (sliderState) {
23998             var renderHash = {
23999                 name: _this._name,
24000                 render: {
24001                     frameId: sliderState.frameId,
24002                     needsRender: sliderState.glNeedsRender,
24003                     render: sliderState.render.bind(sliderState),
24004                     stage: Render_1.GLRenderStage.Background,
24005                 },
24006             };
24007             sliderState.clearGLNeedsRender();
24008             return renderHash;
24009         })
24010             .subscribe(this._container.glRenderer.render$);
24011         this._domRenderSubscription = this._sliderState$
24012             .filter(function (sliderState) {
24013             return sliderState.domNeedsRender;
24014         })
24015             .subscribe(function (sliderState) {
24016             _this._sliderControl.value = (1000 * sliderState.curtain).toString();
24017             var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
24018             _this._sliderControl.style.visibility = visibility;
24019             sliderState.clearDomNeedsRender();
24020         });
24021         this._sliderStateCreator$.next(null);
24022         this._stateSubscription = this._navigator.stateService.currentState$
24023             .map(function (frame) {
24024             return function (sliderState) {
24025                 sliderState.update(frame);
24026                 return sliderState;
24027             };
24028         })
24029             .subscribe(this._sliderStateOperation$);
24030         this._setSliderVisibleSubscription = this._configuration$
24031             .map(function (configuration) {
24032             return configuration.sliderVisible == null || configuration.sliderVisible;
24033         })
24034             .distinctUntilChanged()
24035             .map(function (sliderVisible) {
24036             return function (sliderState) {
24037                 sliderState.sliderVisible = sliderVisible;
24038                 return sliderState;
24039             };
24040         })
24041             .subscribe(this._sliderStateOperation$);
24042         this._setKeysSubscription = this._configuration$
24043             .filter(function (configuration) {
24044             return configuration.keys != null;
24045         })
24046             .switchMap(function (configuration) {
24047             return Observable_1.Observable
24048                 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
24049                 .map(function (nodes) {
24050                 return { background: nodes[0], foreground: nodes[1] };
24051             })
24052                 .zip(_this._navigator.stateService.currentState$.first())
24053                 .map(function (nf) {
24054                 return { nodes: nf[0], state: nf[1].state };
24055             });
24056         })
24057             .subscribe(function (co) {
24058             if (co.state.currentNode != null &&
24059                 co.state.previousNode != null &&
24060                 co.state.currentNode.key === co.nodes.foreground.key &&
24061                 co.state.previousNode.key === co.nodes.background.key) {
24062                 return;
24063             }
24064             if (co.state.currentNode.key === co.nodes.background.key) {
24065                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
24066                 return;
24067             }
24068             if (co.state.currentNode.key === co.nodes.foreground.key &&
24069                 co.state.trajectory.length === 1) {
24070                 _this._navigator.stateService.prependNodes([co.nodes.background]);
24071                 return;
24072             }
24073             _this._navigator.stateService.setNodes([co.nodes.background]);
24074             _this._navigator.stateService.setNodes([co.nodes.foreground]);
24075         }, function (e) {
24076             console.error(e);
24077         });
24078         var previousNode$ = this._navigator.stateService.currentState$
24079             .map(function (frame) {
24080             return frame.state.previousNode;
24081         })
24082             .filter(function (node) {
24083             return node != null;
24084         })
24085             .distinctUntilChanged(undefined, function (node) {
24086             return node.key;
24087         });
24088         this._nodeSubscription = Observable_1.Observable
24089             .merge(previousNode$, this._navigator.stateService.currentNode$)
24090             .filter(function (node) {
24091             return node.pano ?
24092                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
24093                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
24094         })
24095             .mergeMap(function (node) {
24096             var baseImageSize = node.pano ?
24097                 Utils_1.Settings.basePanoramaSize :
24098                 Utils_1.Settings.baseImageSize;
24099             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
24100                 return Observable_1.Observable.empty();
24101             }
24102             return node.cacheImage$(Utils_1.Settings.maxImageSize)
24103                 .map(function (n) {
24104                 return [n.image, n];
24105             })
24106                 .catch(function (error, caught) {
24107                 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
24108                 return Observable_1.Observable.empty();
24109             });
24110         })
24111             .map(function (_a) {
24112             var element = _a[0], node = _a[1];
24113             return function (sliderState) {
24114                 sliderState.updateTexture(element, node);
24115                 return sliderState;
24116             };
24117         })
24118             .subscribe(this._sliderStateOperation$);
24119     };
24120     SliderComponent.prototype._deactivate = function () {
24121         var _this = this;
24122         this._navigator.stateService.state$
24123             .first()
24124             .subscribe(function (state) {
24125             if (state === State_1.State.Waiting) {
24126                 _this._navigator.stateService.traverse();
24127             }
24128         });
24129         this._sliderStateDisposer$.next(null);
24130         this._setKeysSubscription.unsubscribe();
24131         this._setSliderVisibleSubscription.unsubscribe();
24132         this._stateSubscription.unsubscribe();
24133         this._glRenderSubscription.unsubscribe();
24134         this._domRenderSubscription.unsubscribe();
24135         this._nodeSubscription.unsubscribe();
24136         this.configure({ keys: null });
24137         this._sliderControl.removeEventListener("input", this._moveToHandler);
24138         this._sliderControl.removeEventListener("change", this._moveToHandler);
24139         this._container.element.removeChild(this._sliderContainer);
24140         this._moveToHandler = null;
24141         this._sliderControl = null;
24142         this._sliderWrapper = null;
24143         this._sliderContainer = null;
24144     };
24145     SliderComponent.prototype._getDefaultConfiguration = function () {
24146         return {};
24147     };
24148     SliderComponent.prototype._catchCacheNode$ = function (key) {
24149         return this._navigator.graphService.cacheNode$(key)
24150             .catch(function (error, caught) {
24151             console.error("Failed to cache slider node (" + key + ")", error);
24152             return Observable_1.Observable.empty();
24153         });
24154     };
24155     SliderComponent.componentName = "slider";
24156     return SliderComponent;
24157 }(Component_1.Component));
24158 exports.SliderComponent = SliderComponent;
24159 Component_1.ComponentService.register(SliderComponent);
24160 exports.default = SliderComponent;
24161
24162 },{"../../Component":230,"../../Render":236,"../../State":237,"../../Utils":240,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/fromEvent":42,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":74,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/withLatestFrom":85,"rxjs/add/operator/zip":86}],266:[function(require,module,exports){
24163 "use strict";
24164 Object.defineProperty(exports, "__esModule", { value: true });
24165 var CoverState;
24166 (function (CoverState) {
24167     CoverState[CoverState["Hidden"] = 0] = "Hidden";
24168     CoverState[CoverState["Loading"] = 1] = "Loading";
24169     CoverState[CoverState["Visible"] = 2] = "Visible";
24170 })(CoverState = exports.CoverState || (exports.CoverState = {}));
24171
24172 },{}],267:[function(require,module,exports){
24173 "use strict";
24174 Object.defineProperty(exports, "__esModule", { value: true });
24175 var ICoverConfiguration_1 = require("./ICoverConfiguration");
24176 exports.CoverState = ICoverConfiguration_1.CoverState;
24177
24178 },{"./ICoverConfiguration":266}],268:[function(require,module,exports){
24179 "use strict";
24180 /// <reference path="../../../typings/index.d.ts" />
24181 var __extends = (this && this.__extends) || (function () {
24182     var extendStatics = Object.setPrototypeOf ||
24183         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24184         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24185     return function (d, b) {
24186         extendStatics(d, b);
24187         function __() { this.constructor = d; }
24188         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24189     };
24190 })();
24191 Object.defineProperty(exports, "__esModule", { value: true });
24192 require("rxjs/add/operator/switchMap");
24193 require("rxjs/add/operator/withLatestFrom");
24194 var Component_1 = require("../../Component");
24195 var Edge_1 = require("../../Edge");
24196 /**
24197  * The `KeySequenceNavigationHandler` allows the user navigate through a sequence using the
24198  * following key commands:
24199  *
24200  * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
24201  * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
24202  *
24203  * @example
24204  * ```
24205  * var keyboardComponent = viewer.getComponent("keyboard");
24206  *
24207  * keyboardComponent.keySequenceNavigation.disable();
24208  * keyboardComponent.keySequenceNavigation.enable();
24209  *
24210  * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
24211  * ```
24212  */
24213 var KeySequenceNavigationHandler = (function (_super) {
24214     __extends(KeySequenceNavigationHandler, _super);
24215     function KeySequenceNavigationHandler() {
24216         return _super !== null && _super.apply(this, arguments) || this;
24217     }
24218     KeySequenceNavigationHandler.prototype._enable = function () {
24219         var _this = this;
24220         var sequenceEdges$ = this._navigator.stateService.currentNode$
24221             .switchMap(function (node) {
24222             return node.sequenceEdges$;
24223         });
24224         this._keyDownSubscription = this._container.keyboardService.keyDown$
24225             .withLatestFrom(sequenceEdges$)
24226             .subscribe(function (_a) {
24227             var event = _a[0], edgeStatus = _a[1];
24228             var direction = null;
24229             switch (event.keyCode) {
24230                 case 38:// up
24231                     direction = Edge_1.EdgeDirection.Next;
24232                     break;
24233                 case 40:// down
24234                     direction = Edge_1.EdgeDirection.Prev;
24235                     break;
24236                 default:
24237                     return;
24238             }
24239             event.preventDefault();
24240             if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
24241                 return;
24242             }
24243             for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
24244                 var edge = _b[_i];
24245                 if (edge.data.direction === direction) {
24246                     _this._navigator.moveToKey$(edge.to)
24247                         .subscribe(function (n) { return; }, function (e) { console.error(e); });
24248                     return;
24249                 }
24250             }
24251         });
24252     };
24253     KeySequenceNavigationHandler.prototype._disable = function () {
24254         this._keyDownSubscription.unsubscribe();
24255     };
24256     KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
24257         return { keySequenceNavigation: enable };
24258     };
24259     return KeySequenceNavigationHandler;
24260 }(Component_1.HandlerBase));
24261 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
24262 exports.default = KeySequenceNavigationHandler;
24263
24264 },{"../../Component":230,"../../Edge":231,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/withLatestFrom":85}],269:[function(require,module,exports){
24265 "use strict";
24266 /// <reference path="../../../typings/index.d.ts" />
24267 var __extends = (this && this.__extends) || (function () {
24268     var extendStatics = Object.setPrototypeOf ||
24269         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24270         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24271     return function (d, b) {
24272         extendStatics(d, b);
24273         function __() { this.constructor = d; }
24274         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24275     };
24276 })();
24277 Object.defineProperty(exports, "__esModule", { value: true });
24278 require("rxjs/add/operator/switchMap");
24279 require("rxjs/add/operator/withLatestFrom");
24280 var Component_1 = require("../../Component");
24281 var Edge_1 = require("../../Edge");
24282 /**
24283  * The `KeySpatialNavigationHandler` allows the user navigate through a sequence using the
24284  * following key commands:
24285  *
24286  * `Up Arrow`: Step forward.
24287  * `Down Arrow`: Step backward.
24288  * `Left Arrow`: Step to the left.
24289  * `Rigth Arrow`: Step to the right.
24290  * `SHIFT` + `Down Arrow`: Turn around.
24291  * `SHIFT` + `Left Arrow`: Turn to the left.
24292  * `SHIFT` + `Rigth Arrow`: Turn to the right.
24293  *
24294  * @example
24295  * ```
24296  * var keyboardComponent = viewer.getComponent("keyboard");
24297  *
24298  * keyboardComponent.keySpatialNavigation.disable();
24299  * keyboardComponent.keySpatialNavigation.enable();
24300  *
24301  * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
24302  * ```
24303  */
24304 var KeySpatialNavigationHandler = (function (_super) {
24305     __extends(KeySpatialNavigationHandler, _super);
24306     function KeySpatialNavigationHandler(component, container, navigator, spatial) {
24307         var _this = _super.call(this, component, container, navigator) || this;
24308         _this._spatial = spatial;
24309         return _this;
24310     }
24311     KeySpatialNavigationHandler.prototype._enable = function () {
24312         var _this = this;
24313         var spatialEdges$ = this._navigator.stateService.currentNode$
24314             .switchMap(function (node) {
24315             return node.spatialEdges$;
24316         });
24317         this._keyDownSubscription = this._container.keyboardService.keyDown$
24318             .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$)
24319             .subscribe(function (_a) {
24320             var event = _a[0], edgeStatus = _a[1], frame = _a[2];
24321             var pano = frame.state.currentNode.pano;
24322             var direction = null;
24323             switch (event.keyCode) {
24324                 case 37:// left
24325                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
24326                     break;
24327                 case 38:// up
24328                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
24329                     break;
24330                 case 39:// right
24331                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
24332                     break;
24333                 case 40:// down
24334                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
24335                     break;
24336                 default:
24337                     return;
24338             }
24339             event.preventDefault();
24340             if (event.altKey || !edgeStatus.cached ||
24341                 (event.shiftKey && pano)) {
24342                 return;
24343             }
24344             if (!pano) {
24345                 _this._moveDir(direction, edgeStatus);
24346             }
24347             else {
24348                 var shifts = {};
24349                 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
24350                 shifts[Edge_1.EdgeDirection.StepForward] = 0;
24351                 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
24352                 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
24353                 var phi = _this._rotationFromCamera(frame.state.camera).phi;
24354                 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
24355                 var threshold = Math.PI / 4;
24356                 var edges = edgeStatus.edges.filter(function (e) {
24357                     return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
24358                 });
24359                 var smallestAngle = Number.MAX_VALUE;
24360                 var toKey = null;
24361                 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
24362                     var edge = edges_1[_i];
24363                     var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
24364                     if (angle < Math.min(smallestAngle, threshold)) {
24365                         smallestAngle = angle;
24366                         toKey = edge.to;
24367                     }
24368                 }
24369                 if (toKey == null) {
24370                     return;
24371                 }
24372                 _this._moveToKey(toKey);
24373             }
24374         });
24375     };
24376     KeySpatialNavigationHandler.prototype._disable = function () {
24377         this._keyDownSubscription.unsubscribe();
24378     };
24379     KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
24380         return { keySpatialNavigation: enable };
24381     };
24382     KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
24383         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
24384             var edge = _a[_i];
24385             if (edge.data.direction === direction) {
24386                 this._moveToKey(edge.to);
24387                 return;
24388             }
24389         }
24390     };
24391     KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
24392         this._navigator.moveToKey$(key)
24393             .subscribe(function (n) { }, function (e) { console.error(e); });
24394     };
24395     KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
24396         var direction = camera.lookat.clone().sub(camera.position);
24397         var upProjection = direction.clone().dot(camera.up);
24398         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
24399         var phi = Math.atan2(planeProjection.y, planeProjection.x);
24400         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
24401         return { phi: phi, theta: theta };
24402     };
24403     return KeySpatialNavigationHandler;
24404 }(Component_1.HandlerBase));
24405 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
24406 exports.default = KeySpatialNavigationHandler;
24407
24408 },{"../../Component":230,"../../Edge":231,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/withLatestFrom":85}],270:[function(require,module,exports){
24409 "use strict";
24410 /// <reference path="../../../typings/index.d.ts" />
24411 var __extends = (this && this.__extends) || (function () {
24412     var extendStatics = Object.setPrototypeOf ||
24413         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24414         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24415     return function (d, b) {
24416         extendStatics(d, b);
24417         function __() { this.constructor = d; }
24418         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24419     };
24420 })();
24421 Object.defineProperty(exports, "__esModule", { value: true });
24422 require("rxjs/add/operator/withLatestFrom");
24423 var Component_1 = require("../../Component");
24424 /**
24425  * The `KeyZoomHandler` allows the user zoom in and out using the
24426  * following key commands:
24427  *
24428  * `+`: Zoom in.
24429  * `-`: Zoom out.
24430  *
24431  * @example
24432  * ```
24433  * var keyboardComponent = viewer.getComponent("keyboard");
24434  *
24435  * keyboardComponent.keyZoom.disable();
24436  * keyboardComponent.keyZoom.enable();
24437  *
24438  * var isEnabled = keyboardComponent.keyZoom.isEnabled;
24439  * ```
24440  */
24441 var KeyZoomHandler = (function (_super) {
24442     __extends(KeyZoomHandler, _super);
24443     function KeyZoomHandler(component, container, navigator, viewportCoords) {
24444         var _this = _super.call(this, component, container, navigator) || this;
24445         _this._viewportCoords = viewportCoords;
24446         return _this;
24447     }
24448     KeyZoomHandler.prototype._enable = function () {
24449         var _this = this;
24450         this._keyDownSubscription = this._container.keyboardService.keyDown$
24451             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
24452             .subscribe(function (_a) {
24453             var event = _a[0], render = _a[1], transform = _a[2];
24454             if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
24455                 return;
24456             }
24457             var delta = 0;
24458             switch (event.key) {
24459                 case "+":
24460                     delta = 1;
24461                     break;
24462                 case "-":
24463                     delta = -1;
24464                     break;
24465                 default:
24466                     return;
24467             }
24468             event.preventDefault();
24469             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
24470             var reference = transform.projectBasic(unprojected.toArray());
24471             _this._navigator.stateService.zoomIn(delta, reference);
24472         });
24473     };
24474     KeyZoomHandler.prototype._disable = function () {
24475         this._keyDownSubscription.unsubscribe();
24476     };
24477     KeyZoomHandler.prototype._getConfiguration = function (enable) {
24478         return { keyZoom: enable };
24479     };
24480     return KeyZoomHandler;
24481 }(Component_1.HandlerBase));
24482 exports.KeyZoomHandler = KeyZoomHandler;
24483 exports.default = KeyZoomHandler;
24484
24485 },{"../../Component":230,"rxjs/add/operator/withLatestFrom":85}],271:[function(require,module,exports){
24486 "use strict";
24487 var __extends = (this && this.__extends) || (function () {
24488     var extendStatics = Object.setPrototypeOf ||
24489         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24490         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24491     return function (d, b) {
24492         extendStatics(d, b);
24493         function __() { this.constructor = d; }
24494         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24495     };
24496 })();
24497 Object.defineProperty(exports, "__esModule", { value: true });
24498 var Component_1 = require("../../Component");
24499 var Geo_1 = require("../../Geo");
24500 /**
24501  * @class KeyboardComponent
24502  *
24503  * @classdesc Component for keyboard event handling.
24504  *
24505  * To retrive and use the keyboard component
24506  *
24507  * @example
24508  * ```
24509  * var viewer = new Mapillary.Viewer(
24510  *     "<element-id>",
24511  *     "<client-id>",
24512  *     "<my key>");
24513  *
24514  * var keyboardComponent = viewer.getComponent("keyboard");
24515  * ```
24516  */
24517 var KeyboardComponent = (function (_super) {
24518     __extends(KeyboardComponent, _super);
24519     function KeyboardComponent(name, container, navigator) {
24520         var _this = _super.call(this, name, container, navigator) || this;
24521         _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
24522         _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
24523         _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
24524         return _this;
24525     }
24526     Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
24527         /**
24528          * Get key zoom.
24529          *
24530          * @returns {KeyZoomHandler} The key zoom handler.
24531          */
24532         get: function () {
24533             return this._keyZoomHandler;
24534         },
24535         enumerable: true,
24536         configurable: true
24537     });
24538     Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
24539         /**
24540          * Get key sequence navigation.
24541          *
24542          * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
24543          */
24544         get: function () {
24545             return this._keySequenceNavigationHandler;
24546         },
24547         enumerable: true,
24548         configurable: true
24549     });
24550     Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
24551         /**
24552          * Get spatial.
24553          *
24554          * @returns {KeySpatialNavigationHandler} The spatial handler.
24555          */
24556         get: function () {
24557             return this._keySpatialNavigationHandler;
24558         },
24559         enumerable: true,
24560         configurable: true
24561     });
24562     KeyboardComponent.prototype._activate = function () {
24563         var _this = this;
24564         this._configurationSubscription = this._configuration$
24565             .subscribe(function (configuration) {
24566             if (configuration.keyZoom) {
24567                 _this._keyZoomHandler.enable();
24568             }
24569             else {
24570                 _this._keyZoomHandler.disable();
24571             }
24572             if (configuration.keySequenceNavigation) {
24573                 _this._keySequenceNavigationHandler.enable();
24574             }
24575             else {
24576                 _this._keySequenceNavigationHandler.disable();
24577             }
24578             if (configuration.keySpatialNavigation) {
24579                 _this._keySpatialNavigationHandler.enable();
24580             }
24581             else {
24582                 _this._keySpatialNavigationHandler.disable();
24583             }
24584         });
24585     };
24586     KeyboardComponent.prototype._deactivate = function () {
24587         this._configurationSubscription.unsubscribe();
24588     };
24589     KeyboardComponent.prototype._getDefaultConfiguration = function () {
24590         return { keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
24591     };
24592     KeyboardComponent.componentName = "keyboard";
24593     return KeyboardComponent;
24594 }(Component_1.Component));
24595 exports.KeyboardComponent = KeyboardComponent;
24596 Component_1.ComponentService.register(KeyboardComponent);
24597 exports.default = KeyboardComponent;
24598
24599 },{"../../Component":230,"../../Geo":233}],272:[function(require,module,exports){
24600 "use strict";
24601 Object.defineProperty(exports, "__esModule", { value: true });
24602 var MarkerComponent_1 = require("./MarkerComponent");
24603 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
24604 var SimpleMarker_1 = require("./marker/SimpleMarker");
24605 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
24606 var CircleMarker_1 = require("./marker/CircleMarker");
24607 exports.CircleMarker = CircleMarker_1.CircleMarker;
24608
24609 },{"./MarkerComponent":273,"./marker/CircleMarker":276,"./marker/SimpleMarker":278}],273:[function(require,module,exports){
24610 "use strict";
24611 /// <reference path="../../../typings/index.d.ts" />
24612 var __extends = (this && this.__extends) || (function () {
24613     var extendStatics = Object.setPrototypeOf ||
24614         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24615         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24616     return function (d, b) {
24617         extendStatics(d, b);
24618         function __() { this.constructor = d; }
24619         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24620     };
24621 })();
24622 Object.defineProperty(exports, "__esModule", { value: true });
24623 var THREE = require("three");
24624 var when = require("when");
24625 var Observable_1 = require("rxjs/Observable");
24626 require("rxjs/add/observable/combineLatest");
24627 require("rxjs/add/operator/distinctUntilChanged");
24628 require("rxjs/add/operator/map");
24629 var Component_1 = require("../../Component");
24630 var Render_1 = require("../../Render");
24631 var Graph_1 = require("../../Graph");
24632 var Geo_1 = require("../../Geo");
24633 /**
24634  * @class MarkerComponent
24635  *
24636  * @classdesc Component for showing and editing 3D marker objects.
24637  *
24638  * The `add` method is used for adding new markers or replacing
24639  * markers already in the set.
24640  *
24641  * If a marker already in the set has the same
24642  * id as one of the markers added, the old marker will be removed and
24643  * the added marker will take its place.
24644  *
24645  * It is not possible to update markers in the set by updating any properties
24646  * directly on the marker object. Markers need to be replaced by
24647  * re-adding them for updates to geographic position or configuration
24648  * to be reflected.
24649  *
24650  * Markers added to the marker component can be either interactive
24651  * or non-interactive. Different marker types define their behavior.
24652  * Markers with interaction support can be configured with options
24653  * to respond to dragging inside the viewer and be detected when
24654  * retrieving markers from pixel points with the `getMarkerIdAt` method.
24655  *
24656  * To retrive and use the marker component
24657  *
24658  * @example
24659  * ```
24660  * var viewer = new Mapillary.Viewer(
24661  *     "<element-id>",
24662  *     "<client-id>",
24663  *     "<my key>",
24664  *     { component: { marker: true } });
24665  *
24666  * var markerComponent = viewer.getComponent("marker");
24667  * ```
24668  */
24669 var MarkerComponent = (function (_super) {
24670     __extends(MarkerComponent, _super);
24671     function MarkerComponent(name, container, navigator) {
24672         var _this = _super.call(this, name, container, navigator) || this;
24673         _this._relativeGroundAltitude = -2;
24674         _this._geoCoords = new Geo_1.GeoCoords();
24675         _this._graphCalculator = new Graph_1.GraphCalculator();
24676         _this._markerScene = new Component_1.MarkerScene();
24677         _this._markerSet = new Component_1.MarkerSet();
24678         _this._viewportCoords = new Geo_1.ViewportCoords();
24679         return _this;
24680     }
24681     /**
24682      * Add markers to the marker set or replace markers in the marker set.
24683      *
24684      * @description If a marker already in the set has the same
24685      * id as one of the markers added, the old marker will be removed
24686      * the added marker will take its place.
24687      *
24688      * Any marker inside the visible bounding bbox
24689      * will be initialized and placed in the viewer.
24690      *
24691      * @param {Array<Marker>} markers - Markers to add.
24692      *
24693      * @example ```markerComponent.add([marker1, marker2]);```
24694      */
24695     MarkerComponent.prototype.add = function (markers) {
24696         this._markerSet.add(markers);
24697     };
24698     /**
24699      * Returns the marker in the marker set with the specified id, or
24700      * undefined if the id matches no marker.
24701      *
24702      * @param {string} markerId - Id of the marker.
24703      *
24704      * @example ```var marker = markerComponent.get("markerId");```
24705      *
24706      */
24707     MarkerComponent.prototype.get = function (markerId) {
24708         return this._markerSet.get(markerId);
24709     };
24710     /**
24711      * Returns an array of all markers.
24712      *
24713      * @example ```var markers = markerComponent.getAll();```
24714      */
24715     MarkerComponent.prototype.getAll = function () {
24716         return this._markerSet.getAll();
24717     };
24718     /**
24719      * Returns the id of the interactive marker closest to the current camera
24720      * position at the specified point.
24721      *
24722      * @description Notice that the pixelPoint argument requires x, y
24723      * coordinates from pixel space.
24724      *
24725      * With this function, you can use the coordinates provided by mouse
24726      * events to get information out of the marker component.
24727      *
24728      * If no interactive geometry of an interactive marker exist at the pixel
24729      * point, `null` will be returned.
24730      *
24731      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
24732      * @returns {string} Id of the interactive marker closest to the camera. If no
24733      * interactive marker exist at the pixel point, `null` will be returned.
24734      *
24735      * @example
24736      * ```
24737      * markerComponent.getMarkerIdAt([100, 100])
24738      *     .then((markerId) => { console.log(markerId); });
24739      * ```
24740      */
24741     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
24742         var _this = this;
24743         return when.promise(function (resolve, reject) {
24744             _this._container.renderService.renderCamera$
24745                 .first()
24746                 .map(function (render) {
24747                 var viewport = _this._viewportCoords
24748                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
24749                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
24750                 return id;
24751             })
24752                 .subscribe(function (id) {
24753                 resolve(id);
24754             }, function (error) {
24755                 reject(error);
24756             });
24757         });
24758     };
24759     /**
24760      * Check if a marker exist in the marker set.
24761      *
24762      * @param {string} markerId - Id of the marker.
24763      *
24764      * @example ```var markerExists = markerComponent.has("markerId");```
24765      */
24766     MarkerComponent.prototype.has = function (markerId) {
24767         return this._markerSet.has(markerId);
24768     };
24769     /**
24770      * Remove markers with the specified ids from the marker set.
24771      *
24772      * @param {Array<string>} markerIds - Ids for markers to remove.
24773      *
24774      * @example ```markerComponent.remove(["id-1", "id-2"]);```
24775      */
24776     MarkerComponent.prototype.remove = function (markerIds) {
24777         this._markerSet.remove(markerIds);
24778     };
24779     /**
24780      * Remove all markers from the marker set.
24781      *
24782      * @example ```markerComponent.removeAll();```
24783      */
24784     MarkerComponent.prototype.removeAll = function () {
24785         this._markerSet.removeAll();
24786     };
24787     MarkerComponent.prototype._activate = function () {
24788         var _this = this;
24789         var groundAltitude$ = this._navigator.stateService.currentState$
24790             .map(function (frame) {
24791             return frame.state.camera.position.z + _this._relativeGroundAltitude;
24792         })
24793             .distinctUntilChanged(function (a1, a2) {
24794             return Math.abs(a1 - a2) < 0.01;
24795         })
24796             .publishReplay(1)
24797             .refCount();
24798         var geoInitiated$ = Observable_1.Observable
24799             .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
24800             .first()
24801             .map(function () { })
24802             .publishReplay(1)
24803             .refCount();
24804         var clampedConfiguration$ = this._configuration$
24805             .map(function (configuration) {
24806             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
24807         });
24808         var currentlatLon$ = this._navigator.stateService.currentNode$
24809             .map(function (node) { return node.latLon; })
24810             .publishReplay(1)
24811             .refCount();
24812         var visibleBBox$ = Observable_1.Observable
24813             .combineLatest(clampedConfiguration$, currentlatLon$)
24814             .map(function (_a) {
24815             var configuration = _a[0], latLon = _a[1];
24816             return _this._graphCalculator
24817                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
24818         })
24819             .publishReplay(1)
24820             .refCount();
24821         var visibleMarkers$ = Observable_1.Observable
24822             .combineLatest(Observable_1.Observable
24823             .of(this._markerSet)
24824             .concat(this._markerSet.changed$), visibleBBox$)
24825             .map(function (_a) {
24826             var set = _a[0], bbox = _a[1];
24827             return set.search(bbox);
24828         });
24829         this._setChangedSubscription = geoInitiated$
24830             .switchMap(function () {
24831             return visibleMarkers$
24832                 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
24833         })
24834             .subscribe(function (_a) {
24835             var markers = _a[0], reference = _a[1], alt = _a[2];
24836             var geoCoords = _this._geoCoords;
24837             var markerScene = _this._markerScene;
24838             var sceneMarkers = markerScene.markers;
24839             var markersToRemove = Object.assign({}, sceneMarkers);
24840             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24841                 var marker = markers_1[_i];
24842                 if (marker.id in sceneMarkers) {
24843                     delete markersToRemove[marker.id];
24844                 }
24845                 else {
24846                     var point3d = geoCoords
24847                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24848                     markerScene.add(marker, point3d);
24849                 }
24850             }
24851             for (var id in markersToRemove) {
24852                 if (!markersToRemove.hasOwnProperty(id)) {
24853                     continue;
24854                 }
24855                 markerScene.remove(id);
24856             }
24857         });
24858         this._markersUpdatedSubscription = geoInitiated$
24859             .switchMap(function () {
24860             return _this._markerSet.updated$
24861                 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
24862         })
24863             .subscribe(function (_a) {
24864             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
24865             var geoCoords = _this._geoCoords;
24866             var markerScene = _this._markerScene;
24867             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
24868                 var marker = markers_2[_i];
24869                 var exists = markerScene.has(marker.id);
24870                 var visible = marker.latLon.lat > sw.lat &&
24871                     marker.latLon.lat < ne.lat &&
24872                     marker.latLon.lon > sw.lon &&
24873                     marker.latLon.lon < ne.lon;
24874                 if (visible) {
24875                     var point3d = geoCoords
24876                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24877                     markerScene.add(marker, point3d);
24878                 }
24879                 else if (!visible && exists) {
24880                     markerScene.remove(marker.id);
24881                 }
24882             }
24883         });
24884         this._referenceSubscription = this._navigator.stateService.reference$
24885             .skip(1)
24886             .withLatestFrom(groundAltitude$)
24887             .subscribe(function (_a) {
24888             var reference = _a[0], alt = _a[1];
24889             var geoCoords = _this._geoCoords;
24890             var markerScene = _this._markerScene;
24891             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24892                 var marker = _b[_i];
24893                 var point3d = geoCoords
24894                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24895                 markerScene.update(marker.id, point3d);
24896             }
24897         });
24898         this._adjustHeightSubscription = groundAltitude$
24899             .skip(1)
24900             .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
24901             .subscribe(function (_a) {
24902             var alt = _a[0], reference = _a[1], latLon = _a[2];
24903             var geoCoords = _this._geoCoords;
24904             var markerScene = _this._markerScene;
24905             var position = geoCoords
24906                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24907             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24908                 var marker = _b[_i];
24909                 var point3d = geoCoords
24910                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24911                 var distanceX = point3d[0] - position[0];
24912                 var distanceY = point3d[1] - position[1];
24913                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
24914                 if (groundDistance > 50) {
24915                     continue;
24916                 }
24917                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
24918             }
24919         });
24920         this._renderSubscription = this._navigator.stateService.currentState$
24921             .map(function (frame) {
24922             var scene = _this._markerScene;
24923             return {
24924                 name: _this._name,
24925                 render: {
24926                     frameId: frame.id,
24927                     needsRender: scene.needsRender,
24928                     render: scene.render.bind(scene),
24929                     stage: Render_1.GLRenderStage.Foreground,
24930                 },
24931             };
24932         })
24933             .subscribe(this._container.glRenderer.render$);
24934         var hoveredMarkerId$ = Observable_1.Observable
24935             .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
24936             .map(function (_a) {
24937             var render = _a[0], event = _a[1];
24938             var element = _this._container.element;
24939             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24940             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
24941             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
24942             return markerId;
24943         })
24944             .publishReplay(1)
24945             .refCount();
24946         var draggingStarted$ = this._container.mouseService
24947             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24948             .map(function (event) {
24949             return true;
24950         });
24951         var draggingStopped$ = this._container.mouseService
24952             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
24953             .map(function (event) {
24954             return false;
24955         });
24956         var filteredDragging$ = Observable_1.Observable
24957             .merge(draggingStarted$, draggingStopped$)
24958             .startWith(false);
24959         this._dragEventSubscription = draggingStarted$
24960             .withLatestFrom(hoveredMarkerId$)
24961             .merge(Observable_1.Observable
24962             .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
24963             .startWith([false, null])
24964             .pairwise()
24965             .subscribe(function (_a) {
24966             var previous = _a[0], current = _a[1];
24967             var dragging = current[0];
24968             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
24969             var id = dragging ? current[1] : previous[1];
24970             var marker = _this._markerScene.get(id);
24971             var markerEvent = { marker: marker, target: _this, type: eventType };
24972             _this.fire(eventType, markerEvent);
24973         });
24974         var mouseDown$ = Observable_1.Observable
24975             .merge(this._container.mouseService.mouseDown$
24976             .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$
24977             .map(function (event) { return false; }))
24978             .startWith(false);
24979         this._mouseClaimSubscription = Observable_1.Observable
24980             .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$)
24981             .map(function (_a) {
24982             var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
24983             return (!active && markerId != null && mouseDown) || filteredDragging;
24984         })
24985             .distinctUntilChanged()
24986             .subscribe(function (claim) {
24987             if (claim) {
24988                 _this._container.mouseService.claimMouse(_this._name, 1);
24989                 _this._container.mouseService.claimWheel(_this._name, 1);
24990             }
24991             else {
24992                 _this._container.mouseService.unclaimMouse(_this._name);
24993                 _this._container.mouseService.unclaimWheel(_this._name);
24994             }
24995         });
24996         var offset$ = this._container.mouseService
24997             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24998             .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
24999             .map(function (_a) {
25000             var e = _a[0], id = _a[1], r = _a[2];
25001             var marker = _this._markerScene.get(id);
25002             var element = _this._container.element;
25003             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
25004             var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
25005             var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
25006             return [marker, offset, r];
25007         })
25008             .publishReplay(1)
25009             .refCount();
25010         this._updateMarkerSubscription = this._container.mouseService
25011             .filtered$(this._name, this._container.mouseService.mouseDrag$)
25012             .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
25013             .subscribe(function (_a) {
25014             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
25015             if (!_this._markerScene.has(marker.id)) {
25016                 return;
25017             }
25018             var element = _this._container.element;
25019             var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
25020             var groundX = canvasX - offset[0];
25021             var groundY = canvasY - offset[1];
25022             var _d = _this._viewportCoords
25023                 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
25024             var direction = new THREE.Vector3(viewportX, viewportY, 1)
25025                 .unproject(render.perspective)
25026                 .sub(render.perspective.position)
25027                 .normalize();
25028             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
25029             if (distance < 0) {
25030                 return;
25031             }
25032             var intersection = direction
25033                 .clone()
25034                 .multiplyScalar(distance)
25035                 .add(render.perspective.position);
25036             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
25037             var _e = _this._geoCoords
25038                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
25039             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
25040             _this._markerSet.update(marker);
25041             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
25042             _this.fire(MarkerComponent.changed, markerEvent);
25043         });
25044     };
25045     MarkerComponent.prototype._deactivate = function () {
25046         this._adjustHeightSubscription.unsubscribe();
25047         this._dragEventSubscription.unsubscribe();
25048         this._markersUpdatedSubscription.unsubscribe();
25049         this._mouseClaimSubscription.unsubscribe();
25050         this._referenceSubscription.unsubscribe();
25051         this._renderSubscription.unsubscribe();
25052         this._setChangedSubscription.unsubscribe();
25053         this._updateMarkerSubscription.unsubscribe();
25054         this._markerScene.clear();
25055     };
25056     MarkerComponent.prototype._getDefaultConfiguration = function () {
25057         return { visibleBBoxSize: 100 };
25058     };
25059     MarkerComponent.componentName = "marker";
25060     /**
25061      * Fired when the position of a marker is changed.
25062      * @event
25063      * @type {IMarkerEvent} markerEvent - Marker event data.
25064      * @example
25065      * ```
25066      * markerComponent.on("changed", function(e) {
25067      *     console.log(e.marker.id, e.marker.latLon);
25068      * });
25069      * ```
25070      */
25071     MarkerComponent.changed = "changed";
25072     /**
25073      * Fired when a marker drag interaction starts.
25074      * @event
25075      * @type {IMarkerEvent} markerEvent - Marker event data.
25076      * @example
25077      * ```
25078      * markerComponent.on("dragstart", function(e) {
25079      *     console.log(e.marker.id, e.marker.latLon);
25080      * });
25081      * ```
25082      */
25083     MarkerComponent.dragstart = "dragstart";
25084     /**
25085      * Fired when a marker drag interaction ends.
25086      * @event
25087      * @type {IMarkerEvent} markerEvent - Marker event data.
25088      * @example
25089      * ```
25090      * markerComponent.on("dragend", function(e) {
25091      *     console.log(e.marker.id, e.marker.latLon);
25092      * });
25093      * ```
25094      */
25095     MarkerComponent.dragend = "dragend";
25096     return MarkerComponent;
25097 }(Component_1.Component));
25098 exports.MarkerComponent = MarkerComponent;
25099 Component_1.ComponentService.register(MarkerComponent);
25100 exports.default = MarkerComponent;
25101
25102 },{"../../Component":230,"../../Geo":233,"../../Graph":234,"../../Render":236,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"three":180,"when":227}],274:[function(require,module,exports){
25103 "use strict";
25104 /// <reference path="../../../typings/index.d.ts" />
25105 Object.defineProperty(exports, "__esModule", { value: true });
25106 var THREE = require("three");
25107 var MarkerScene = (function () {
25108     function MarkerScene(scene, raycaster) {
25109         this._needsRender = false;
25110         this._interactiveObjects = [];
25111         this._markers = {};
25112         this._objectMarkers = {};
25113         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
25114         this._scene = !!scene ? scene : new THREE.Scene();
25115     }
25116     Object.defineProperty(MarkerScene.prototype, "markers", {
25117         get: function () {
25118             return this._markers;
25119         },
25120         enumerable: true,
25121         configurable: true
25122     });
25123     Object.defineProperty(MarkerScene.prototype, "needsRender", {
25124         get: function () {
25125             return this._needsRender;
25126         },
25127         enumerable: true,
25128         configurable: true
25129     });
25130     MarkerScene.prototype.add = function (marker, position) {
25131         if (marker.id in this._markers) {
25132             this._dispose(marker.id);
25133         }
25134         marker.createGeometry(position);
25135         this._scene.add(marker.geometry);
25136         this._markers[marker.id] = marker;
25137         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
25138             var interactiveObject = _a[_i];
25139             this._interactiveObjects.push(interactiveObject);
25140             this._objectMarkers[interactiveObject.uuid] = marker.id;
25141         }
25142         this._needsRender = true;
25143     };
25144     MarkerScene.prototype.clear = function () {
25145         for (var id in this._markers) {
25146             if (!this._markers.hasOwnProperty) {
25147                 continue;
25148             }
25149             this._dispose(id);
25150         }
25151         this._needsRender = true;
25152     };
25153     MarkerScene.prototype.get = function (id) {
25154         return this._markers[id];
25155     };
25156     MarkerScene.prototype.getAll = function () {
25157         var _this = this;
25158         return Object
25159             .keys(this._markers)
25160             .map(function (id) { return _this._markers[id]; });
25161     };
25162     MarkerScene.prototype.has = function (id) {
25163         return id in this._markers;
25164     };
25165     MarkerScene.prototype.intersectObjects = function (_a, camera) {
25166         var viewportX = _a[0], viewportY = _a[1];
25167         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
25168         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
25169         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
25170             var intersect = intersects_1[_i];
25171             if (intersect.object.uuid in this._objectMarkers) {
25172                 return this._objectMarkers[intersect.object.uuid];
25173             }
25174         }
25175         return null;
25176     };
25177     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
25178         if (!(id in this._markers)) {
25179             return;
25180         }
25181         this._markers[id].lerpAltitude(alt, alpha);
25182         this._needsRender = true;
25183     };
25184     MarkerScene.prototype.remove = function (id) {
25185         if (!(id in this._markers)) {
25186             return;
25187         }
25188         this._dispose(id);
25189         this._needsRender = true;
25190     };
25191     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
25192         renderer.render(this._scene, perspectiveCamera);
25193         this._needsRender = false;
25194     };
25195     MarkerScene.prototype.update = function (id, position, latLon) {
25196         if (!(id in this._markers)) {
25197             return;
25198         }
25199         var marker = this._markers[id];
25200         marker.updatePosition(position, latLon);
25201         this._needsRender = true;
25202     };
25203     MarkerScene.prototype._dispose = function (id) {
25204         var marker = this._markers[id];
25205         this._scene.remove(marker.geometry);
25206         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
25207             var interactiveObject = _a[_i];
25208             var index = this._interactiveObjects.indexOf(interactiveObject);
25209             if (index !== -1) {
25210                 this._interactiveObjects.splice(index, 1);
25211             }
25212             else {
25213                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
25214             }
25215             delete this._objectMarkers[interactiveObject.uuid];
25216         }
25217         marker.disposeGeometry();
25218         delete this._markers[id];
25219     };
25220     return MarkerScene;
25221 }());
25222 exports.MarkerScene = MarkerScene;
25223 exports.default = MarkerScene;
25224
25225 },{"three":180}],275:[function(require,module,exports){
25226 "use strict";
25227 /// <reference path="../../../typings/index.d.ts" />
25228 Object.defineProperty(exports, "__esModule", { value: true });
25229 var rbush = require("rbush");
25230 var Subject_1 = require("rxjs/Subject");
25231 require("rxjs/add/operator/map");
25232 require("rxjs/add/operator/publishReplay");
25233 require("rxjs/add/operator/scan");
25234 var MarkerSet = (function () {
25235     function MarkerSet() {
25236         this._hash = {};
25237         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
25238         this._indexChanged$ = new Subject_1.Subject();
25239         this._updated$ = new Subject_1.Subject();
25240     }
25241     Object.defineProperty(MarkerSet.prototype, "changed$", {
25242         get: function () {
25243             return this._indexChanged$;
25244         },
25245         enumerable: true,
25246         configurable: true
25247     });
25248     Object.defineProperty(MarkerSet.prototype, "updated$", {
25249         get: function () {
25250             return this._updated$;
25251         },
25252         enumerable: true,
25253         configurable: true
25254     });
25255     MarkerSet.prototype.add = function (markers) {
25256         var updated = [];
25257         var hash = this._hash;
25258         var index = this._index;
25259         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
25260             var marker = markers_1[_i];
25261             var id = marker.id;
25262             if (id in hash) {
25263                 index.remove(hash[id]);
25264                 updated.push(marker);
25265             }
25266             var item = {
25267                 lat: marker.latLon.lat,
25268                 lon: marker.latLon.lon,
25269                 marker: marker,
25270             };
25271             hash[id] = item;
25272             index.insert(item);
25273         }
25274         if (updated.length > 0) {
25275             this._updated$.next(updated);
25276         }
25277         if (markers.length > updated.length) {
25278             this._indexChanged$.next(this);
25279         }
25280     };
25281     MarkerSet.prototype.has = function (id) {
25282         return id in this._hash;
25283     };
25284     MarkerSet.prototype.get = function (id) {
25285         return this.has(id) ? this._hash[id].marker : undefined;
25286     };
25287     MarkerSet.prototype.getAll = function () {
25288         return this._index
25289             .all()
25290             .map(function (indexItem) {
25291             return indexItem.marker;
25292         });
25293     };
25294     MarkerSet.prototype.remove = function (ids) {
25295         var hash = this._hash;
25296         var index = this._index;
25297         var changed = false;
25298         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
25299             var id = ids_1[_i];
25300             if (!(id in hash)) {
25301                 continue;
25302             }
25303             var item = hash[id];
25304             index.remove(item);
25305             delete hash[id];
25306             changed = true;
25307         }
25308         if (changed) {
25309             this._indexChanged$.next(this);
25310         }
25311     };
25312     MarkerSet.prototype.removeAll = function () {
25313         this._hash = {};
25314         this._index.clear();
25315         this._indexChanged$.next(this);
25316     };
25317     MarkerSet.prototype.search = function (_a) {
25318         var sw = _a[0], ne = _a[1];
25319         return this._index
25320             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
25321             .map(function (indexItem) {
25322             return indexItem.marker;
25323         });
25324     };
25325     MarkerSet.prototype.update = function (marker) {
25326         var hash = this._hash;
25327         var index = this._index;
25328         var id = marker.id;
25329         if (!(id in hash)) {
25330             return;
25331         }
25332         index.remove(hash[id]);
25333         var item = {
25334             lat: marker.latLon.lat,
25335             lon: marker.latLon.lon,
25336             marker: marker,
25337         };
25338         hash[id] = item;
25339         index.insert(item);
25340     };
25341     return MarkerSet;
25342 }());
25343 exports.MarkerSet = MarkerSet;
25344 exports.default = MarkerSet;
25345
25346 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74}],276:[function(require,module,exports){
25347 "use strict";
25348 /// <reference path="../../../../typings/index.d.ts" />
25349 var __extends = (this && this.__extends) || (function () {
25350     var extendStatics = Object.setPrototypeOf ||
25351         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25352         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25353     return function (d, b) {
25354         extendStatics(d, b);
25355         function __() { this.constructor = d; }
25356         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25357     };
25358 })();
25359 Object.defineProperty(exports, "__esModule", { value: true });
25360 var THREE = require("three");
25361 var Component_1 = require("../../../Component");
25362 /**
25363  * @class CircleMarker
25364  *
25365  * @classdesc Non-interactive marker with a flat circle shape. The circle
25366  * marker can not be configured to be interactive.
25367  *
25368  * Circle marker properties can not be updated after creation.
25369  *
25370  * To create and add one `CircleMarker` with default configuration
25371  * and one with configuration use
25372  *
25373  * @example
25374  * ```
25375  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
25376  *     "id-1",
25377  *     { lat: 0, lon: 0, });
25378  *
25379  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
25380  *     "id-2",
25381  *     { lat: 0, lon: 0, },
25382  *     {
25383  *         color: "#0Ff",
25384  *         opacity: 0.3,
25385  *         radius: 0.7,
25386  *     });
25387  *
25388  * markerComponent.add([defaultMarker, configuredMarker]);
25389  * ```
25390  */
25391 var CircleMarker = (function (_super) {
25392     __extends(CircleMarker, _super);
25393     function CircleMarker(id, latLon, options) {
25394         var _this = _super.call(this, id, latLon) || this;
25395         options = !!options ? options : {};
25396         _this._color = options.color != null ? options.color : 0xffffff;
25397         _this._opacity = options.opacity != null ? options.opacity : 0.4;
25398         _this._radius = options.radius != null ? options.radius : 1;
25399         return _this;
25400     }
25401     CircleMarker.prototype._createGeometry = function (position) {
25402         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
25403             color: this._color,
25404             opacity: this._opacity,
25405             transparent: true,
25406         }));
25407         circle.up.fromArray([0, 0, 1]);
25408         circle.renderOrder = -1;
25409         var group = new THREE.Object3D();
25410         group.add(circle);
25411         group.position.fromArray(position);
25412         this._geometry = group;
25413     };
25414     CircleMarker.prototype._disposeGeometry = function () {
25415         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25416             var mesh = _a[_i];
25417             mesh.geometry.dispose();
25418             mesh.material.dispose();
25419         }
25420     };
25421     CircleMarker.prototype._getInteractiveObjects = function () {
25422         return [];
25423     };
25424     return CircleMarker;
25425 }(Component_1.Marker));
25426 exports.CircleMarker = CircleMarker;
25427 exports.default = CircleMarker;
25428
25429 },{"../../../Component":230,"three":180}],277:[function(require,module,exports){
25430 "use strict";
25431 /// <reference path="../../../../typings/index.d.ts" />
25432 Object.defineProperty(exports, "__esModule", { value: true });
25433 /**
25434  * @class Marker
25435  *
25436  * @classdesc Represents an abstract marker class that should be extended
25437  * by marker implementations used in the marker component.
25438  */
25439 var Marker = (function () {
25440     function Marker(id, latLon) {
25441         this._id = id;
25442         this._latLon = latLon;
25443     }
25444     Object.defineProperty(Marker.prototype, "id", {
25445         /**
25446          * Get id.
25447          * @returns {string} The id of the marker.
25448          */
25449         get: function () {
25450             return this._id;
25451         },
25452         enumerable: true,
25453         configurable: true
25454     });
25455     Object.defineProperty(Marker.prototype, "geometry", {
25456         get: function () {
25457             return this._geometry;
25458         },
25459         enumerable: true,
25460         configurable: true
25461     });
25462     Object.defineProperty(Marker.prototype, "latLon", {
25463         /**
25464          * Get lat lon.
25465          * @returns {ILatLon} The geographic coordinates of the marker.
25466          */
25467         get: function () {
25468             return this._latLon;
25469         },
25470         enumerable: true,
25471         configurable: true
25472     });
25473     Marker.prototype.createGeometry = function (position) {
25474         if (!!this._geometry) {
25475             return;
25476         }
25477         this._createGeometry(position);
25478         // update matrix world if raycasting occurs before first render
25479         this._geometry.updateMatrixWorld(true);
25480     };
25481     Marker.prototype.disposeGeometry = function () {
25482         if (!this._geometry) {
25483             return;
25484         }
25485         this._disposeGeometry();
25486         this._geometry = undefined;
25487     };
25488     Marker.prototype.getInteractiveObjects = function () {
25489         if (!this._geometry) {
25490             return [];
25491         }
25492         return this._getInteractiveObjects();
25493     };
25494     Marker.prototype.lerpAltitude = function (alt, alpha) {
25495         if (!this._geometry) {
25496             return;
25497         }
25498         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
25499     };
25500     Marker.prototype.updatePosition = function (position, latLon) {
25501         if (!!latLon) {
25502             this._latLon.lat = latLon.lat;
25503             this._latLon.lon = latLon.lon;
25504         }
25505         if (!this._geometry) {
25506             return;
25507         }
25508         this._geometry.position.fromArray(position);
25509         this._geometry.updateMatrixWorld(true);
25510     };
25511     return Marker;
25512 }());
25513 exports.Marker = Marker;
25514 exports.default = Marker;
25515
25516 },{}],278:[function(require,module,exports){
25517 "use strict";
25518 /// <reference path="../../../../typings/index.d.ts" />
25519 var __extends = (this && this.__extends) || (function () {
25520     var extendStatics = Object.setPrototypeOf ||
25521         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25522         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25523     return function (d, b) {
25524         extendStatics(d, b);
25525         function __() { this.constructor = d; }
25526         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25527     };
25528 })();
25529 Object.defineProperty(exports, "__esModule", { value: true });
25530 var THREE = require("three");
25531 var Component_1 = require("../../../Component");
25532 /**
25533  * @class SimpleMarker
25534  *
25535  * @classdesc Interactive marker with ice cream shape. The sphere
25536  * inside the ice cream can be configured to be interactive.
25537  *
25538  * Simple marker properties can not be updated after creation.
25539  *
25540  * To create and add one `SimpleMarker` with default configuration
25541  * (non-interactive) and one interactive with configuration use
25542  *
25543  * @example
25544  * ```
25545  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
25546  *     "id-1",
25547  *     { lat: 0, lon: 0, });
25548  *
25549  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
25550  *     "id-2",
25551  *     { lat: 0, lon: 0, },
25552  *     {
25553  *         ballColor: "#00f",
25554  *         ballOpacity: 0.5,
25555  *         color: "#00f",
25556  *         interactive: true,
25557  *         opacity: 0.3,
25558  *         radius: 0.7,
25559  *     });
25560  *
25561  * markerComponent.add([defaultMarker, interactiveMarker]);
25562  * ```
25563  */
25564 var SimpleMarker = (function (_super) {
25565     __extends(SimpleMarker, _super);
25566     function SimpleMarker(id, latLon, options) {
25567         var _this = _super.call(this, id, latLon) || this;
25568         options = !!options ? options : {};
25569         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
25570         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
25571         _this._circleToRayAngle = 2;
25572         _this._color = options.color != null ? options.color : 0xff0000;
25573         _this._interactive = !!options.interactive;
25574         _this._opacity = options.opacity != null ? options.opacity : 0.4;
25575         _this._radius = options.radius != null ? options.radius : 1;
25576         return _this;
25577     }
25578     SimpleMarker.prototype._createGeometry = function (position) {
25579         var radius = this._radius;
25580         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
25581             color: this._color,
25582             opacity: this._opacity,
25583             shading: THREE.SmoothShading,
25584             transparent: true,
25585         }));
25586         cone.renderOrder = 1;
25587         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
25588             color: this._ballColor,
25589             opacity: this._ballOpacity,
25590             shading: THREE.SmoothShading,
25591             transparent: true,
25592         }));
25593         ball.position.z = this._markerHeight(radius);
25594         var group = new THREE.Object3D();
25595         group.add(ball);
25596         group.add(cone);
25597         group.position.fromArray(position);
25598         this._geometry = group;
25599     };
25600     SimpleMarker.prototype._disposeGeometry = function () {
25601         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25602             var mesh = _a[_i];
25603             mesh.geometry.dispose();
25604             mesh.material.dispose();
25605         }
25606     };
25607     SimpleMarker.prototype._getInteractiveObjects = function () {
25608         return this._interactive ? [this._geometry.children[0]] : [];
25609     };
25610     SimpleMarker.prototype._markerHeight = function (radius) {
25611         var t = Math.tan(Math.PI - this._circleToRayAngle);
25612         return radius * Math.sqrt(1 + t * t);
25613     };
25614     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
25615         var geometry = new THREE.Geometry();
25616         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
25617         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
25618         var height = this._markerHeight(radius);
25619         var vertices = [];
25620         for (var y = 0; y <= heightSegments; ++y) {
25621             var verticesRow = [];
25622             for (var x = 0; x <= widthSegments; ++x) {
25623                 var u = x / widthSegments * Math.PI * 2;
25624                 var v = y / heightSegments * Math.PI;
25625                 var r = void 0;
25626                 if (v < this._circleToRayAngle) {
25627                     r = radius;
25628                 }
25629                 else {
25630                     var t = Math.tan(v - this._circleToRayAngle);
25631                     r = radius * Math.sqrt(1 + t * t);
25632                 }
25633                 var vertex = new THREE.Vector3();
25634                 vertex.x = r * Math.cos(u) * Math.sin(v);
25635                 vertex.y = r * Math.sin(u) * Math.sin(v);
25636                 vertex.z = r * Math.cos(v) + height;
25637                 geometry.vertices.push(vertex);
25638                 verticesRow.push(geometry.vertices.length - 1);
25639             }
25640             vertices.push(verticesRow);
25641         }
25642         for (var y = 0; y < heightSegments; ++y) {
25643             for (var x = 0; x < widthSegments; ++x) {
25644                 var v1 = vertices[y][x + 1];
25645                 var v2 = vertices[y][x];
25646                 var v3 = vertices[y + 1][x];
25647                 var v4 = vertices[y + 1][x + 1];
25648                 var n1 = geometry.vertices[v1].clone().normalize();
25649                 var n2 = geometry.vertices[v2].clone().normalize();
25650                 var n3 = geometry.vertices[v3].clone().normalize();
25651                 var n4 = geometry.vertices[v4].clone().normalize();
25652                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
25653                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
25654             }
25655         }
25656         geometry.computeFaceNormals();
25657         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
25658         return geometry;
25659     };
25660     return SimpleMarker;
25661 }(Component_1.Marker));
25662 exports.SimpleMarker = SimpleMarker;
25663 exports.default = SimpleMarker;
25664
25665 },{"../../../Component":230,"three":180}],279:[function(require,module,exports){
25666 "use strict";
25667 /// <reference path="../../../typings/index.d.ts" />
25668 var __extends = (this && this.__extends) || (function () {
25669     var extendStatics = Object.setPrototypeOf ||
25670         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25671         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25672     return function (d, b) {
25673         extendStatics(d, b);
25674         function __() { this.constructor = d; }
25675         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25676     };
25677 })();
25678 Object.defineProperty(exports, "__esModule", { value: true });
25679 var Observable_1 = require("rxjs/Observable");
25680 var Component_1 = require("../../Component");
25681 /**
25682  * The `BounceHandler` ensures that the viewer bounces back to the image
25683  * when drag panning outside of the image edge.
25684  */
25685 var BounceHandler = (function (_super) {
25686     __extends(BounceHandler, _super);
25687     function BounceHandler(component, container, navigator, viewportCoords, spatial) {
25688         var _this = _super.call(this, component, container, navigator) || this;
25689         _this._spatial = spatial;
25690         _this._viewportCoords = viewportCoords;
25691         _this._basicDistanceThreshold = 1e-3;
25692         _this._basicRotationThreshold = 5e-2;
25693         _this._bounceCoeff = 1e-1;
25694         return _this;
25695     }
25696     BounceHandler.prototype._enable = function () {
25697         var _this = this;
25698         var inTransition$ = this._navigator.stateService.currentState$
25699             .map(function (frame) {
25700             return frame.state.alpha < 1;
25701         });
25702         this._bounceSubscription = Observable_1.Observable
25703             .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
25704             .map(function (noForce) {
25705             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25706         })
25707             .distinctUntilChanged()
25708             .switchMap(function (noForce) {
25709             return noForce ?
25710                 Observable_1.Observable.empty() :
25711                 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
25712         })
25713             .subscribe(function (args) {
25714             var renderCamera = args[0];
25715             var perspectiveCamera = renderCamera.perspective;
25716             var transform = args[1];
25717             if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
25718                 return;
25719             }
25720             if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
25721                 return;
25722             }
25723             var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
25724             var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
25725             if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
25726                 return;
25727             }
25728             var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
25729             var basicX = 0;
25730             var basicY = 0;
25731             if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
25732                 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
25733                 return;
25734             }
25735             if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
25736                 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
25737                 return;
25738             }
25739             var coeff = _this._bounceCoeff;
25740             if (basicDistances[1] > 0 && basicDistances[3] === 0) {
25741                 basicX = -coeff * basicDistances[1];
25742             }
25743             else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
25744                 basicX = coeff * basicDistances[3];
25745             }
25746             else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
25747                 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
25748             }
25749             if (basicDistances[0] > 0 && basicDistances[2] === 0) {
25750                 basicY = coeff * basicDistances[0];
25751             }
25752             else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
25753                 basicY = -coeff * basicDistances[2];
25754             }
25755             else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
25756                 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
25757             }
25758             var rotationThreshold = _this._basicRotationThreshold;
25759             basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
25760             basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
25761             _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
25762         });
25763     };
25764     BounceHandler.prototype._disable = function () {
25765         this._bounceSubscription.unsubscribe();
25766     };
25767     BounceHandler.prototype._getConfiguration = function (enable) {
25768         return {};
25769     };
25770     return BounceHandler;
25771 }(Component_1.HandlerBase));
25772 exports.BounceHandler = BounceHandler;
25773 exports.default = BounceHandler;
25774
25775 },{"../../Component":230,"rxjs/Observable":29}],280:[function(require,module,exports){
25776 "use strict";
25777 var __extends = (this && this.__extends) || (function () {
25778     var extendStatics = Object.setPrototypeOf ||
25779         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25780         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25781     return function (d, b) {
25782         extendStatics(d, b);
25783         function __() { this.constructor = d; }
25784         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25785     };
25786 })();
25787 Object.defineProperty(exports, "__esModule", { value: true });
25788 var Observable_1 = require("rxjs/Observable");
25789 var Component_1 = require("../../Component");
25790 /**
25791  * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
25792  *
25793  * @example
25794  * ```
25795  * var mouseComponent = viewer.getComponent("mouse");
25796  *
25797  * mouseComponent.doubleClickZoom.disable();
25798  * mouseComponent.doubleClickZoom.enable();
25799  *
25800  * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
25801  * ```
25802  */
25803 var DoubleClickZoomHandler = (function (_super) {
25804     __extends(DoubleClickZoomHandler, _super);
25805     function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
25806         var _this = _super.call(this, component, container, navigator) || this;
25807         _this._viewportCoords = viewportCoords;
25808         return _this;
25809     }
25810     DoubleClickZoomHandler.prototype._enable = function () {
25811         var _this = this;
25812         this._zoomSubscription = Observable_1.Observable
25813             .merge(this._container.mouseService
25814             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
25815             .map(function (e) {
25816             var touch = e.touches[0];
25817             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
25818         }))
25819             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25820             .subscribe(function (_a) {
25821             var event = _a[0], render = _a[1], transform = _a[2];
25822             var element = _this._container.element;
25823             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25824             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25825             var reference = transform.projectBasic(unprojected.toArray());
25826             var delta = !!event.shiftKey ? -1 : 1;
25827             _this._navigator.stateService.zoomIn(delta, reference);
25828         });
25829     };
25830     DoubleClickZoomHandler.prototype._disable = function () {
25831         this._zoomSubscription.unsubscribe();
25832     };
25833     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
25834         return { doubleClickZoom: enable };
25835     };
25836     return DoubleClickZoomHandler;
25837 }(Component_1.HandlerBase));
25838 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
25839 exports.default = DoubleClickZoomHandler;
25840
25841 },{"../../Component":230,"rxjs/Observable":29}],281:[function(require,module,exports){
25842 "use strict";
25843 /// <reference path="../../../typings/index.d.ts" />
25844 var __extends = (this && this.__extends) || (function () {
25845     var extendStatics = Object.setPrototypeOf ||
25846         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25847         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25848     return function (d, b) {
25849         extendStatics(d, b);
25850         function __() { this.constructor = d; }
25851         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25852     };
25853 })();
25854 Object.defineProperty(exports, "__esModule", { value: true });
25855 var THREE = require("three");
25856 var Observable_1 = require("rxjs/Observable");
25857 require("rxjs/add/operator/concat");
25858 require("rxjs/add/operator/sample");
25859 require("rxjs/add/operator/takeWhile");
25860 var Component_1 = require("../../Component");
25861 /**
25862  * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
25863  *
25864  * @example
25865  * ```
25866  * var mouseComponent = viewer.getComponent("mouse");
25867  *
25868  * mouseComponent.dragPan.disable();
25869  * mouseComponent.dragPan.enable();
25870  *
25871  * var isEnabled = mouseComponent.dragPan.isEnabled;
25872  * ```
25873  */
25874 var DragPanHandler = (function (_super) {
25875     __extends(DragPanHandler, _super);
25876     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
25877         var _this = _super.call(this, component, container, navigator) || this;
25878         _this._spatial = spatial;
25879         _this._viewportCoords = viewportCoords;
25880         _this._basicRotationThreshold = 5e-2;
25881         _this._forceCoeff = 2e-1;
25882         return _this;
25883     }
25884     DragPanHandler.prototype._enable = function () {
25885         var _this = this;
25886         var draggingStarted$ = this._container.mouseService
25887             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
25888             .map(function (event) {
25889             return true;
25890         });
25891         var draggingStopped$ = this._container.mouseService
25892             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
25893             .map(function (event) {
25894             return false;
25895         });
25896         this._activeMouseSubscription = Observable_1.Observable
25897             .merge(draggingStarted$, draggingStopped$)
25898             .subscribe(this._container.mouseService.activate$);
25899         this._preventDefaultSubscription = Observable_1.Observable
25900             .merge(draggingStarted$, draggingStopped$)
25901             .switchMap(function (dragging) {
25902             return dragging ?
25903                 _this._container.mouseService.documentMouseMove$ :
25904                 Observable_1.Observable.empty();
25905         })
25906             .merge(this._container.touchService.touchMove$)
25907             .subscribe(function (event) {
25908             event.preventDefault(); // prevent selection of content outside the viewer
25909         });
25910         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
25911             .map(function (event) {
25912             return true;
25913         });
25914         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
25915             .map(function (event) {
25916             return false;
25917         });
25918         this._activeTouchSubscription = Observable_1.Observable
25919             .merge(touchMovingStarted$, touchMovingStopped$)
25920             .subscribe(this._container.touchService.activate$);
25921         var basicRotation$ = this._navigator.stateService.currentState$
25922             .map(function (frame) {
25923             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
25924         })
25925             .distinctUntilChanged()
25926             .switchMap(function (enable) {
25927             if (!enable) {
25928                 return Observable_1.Observable.empty();
25929             }
25930             var mouseDrag$ = _this._container.mouseService
25931                 .filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$)
25932                 .switchMap(function (mouseDragStart) {
25933                 return Observable_1.Observable
25934                     .of(mouseDragStart)
25935                     .concat(_this._container.mouseService
25936                     .filtered$(_this._component.name, _this._container.mouseService.mouseDrag$))
25937                     .merge(_this._container.mouseService
25938                     .filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
25939                     .map(function (e) {
25940                     return null;
25941                 }))
25942                     .takeWhile(function (e) {
25943                     return !!e;
25944                 })
25945                     .startWith(null);
25946             })
25947                 .pairwise()
25948                 .filter(function (pair) {
25949                 return pair[0] != null && pair[1] != null;
25950             });
25951             var singleTouchDrag$ = Observable_1.Observable
25952                 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
25953                 .map(function (event) {
25954                 return event != null && event.touches.length > 0 ?
25955                     event.touches[0] : null;
25956             })
25957                 .pairwise()
25958                 .filter(function (pair) {
25959                 return pair[0] != null && pair[1] != null;
25960             });
25961             return Observable_1.Observable
25962                 .merge(mouseDrag$, singleTouchDrag$);
25963         })
25964             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
25965             .map(function (_a) {
25966             var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
25967             var camera = c.clone();
25968             var previousEvent = events[0];
25969             var event = events[1];
25970             var movementX = event.clientX - previousEvent.clientX;
25971             var movementY = event.clientY - previousEvent.clientY;
25972             var element = _this._container.element;
25973             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25974             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
25975                 .sub(render.perspective.position);
25976             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
25977                 .sub(render.perspective.position);
25978             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
25979                 .sub(render.perspective.position);
25980             var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
25981             var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
25982             var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
25983             var upQuaternionInverse = upQuaternion.clone().inverse();
25984             var offset = new THREE.Vector3();
25985             offset.copy(camera.lookat).sub(camera.position);
25986             offset.applyQuaternion(upQuaternion);
25987             var length = offset.length();
25988             var phi = Math.atan2(offset.y, offset.x);
25989             phi += deltaPhi;
25990             var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
25991             theta += deltaTheta;
25992             theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
25993             offset.x = Math.sin(theta) * Math.cos(phi);
25994             offset.y = Math.sin(theta) * Math.sin(phi);
25995             offset.z = Math.cos(theta);
25996             offset.applyQuaternion(upQuaternionInverse);
25997             var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
25998             var basic = transform.projectBasic(lookat.toArray());
25999             var original = transform.projectBasic(camera.lookat.toArray());
26000             var x = basic[0] - original[0];
26001             var y = basic[1] - original[1];
26002             if (Math.abs(x) > 1) {
26003                 x = 0;
26004             }
26005             else if (x > 0.5) {
26006                 x = x - 1;
26007             }
26008             else if (x < -0.5) {
26009                 x = x + 1;
26010             }
26011             var rotationThreshold = _this._basicRotationThreshold;
26012             x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
26013             y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
26014             if (transform.fullPano) {
26015                 return [x, y];
26016             }
26017             var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
26018             var coeff = _this._forceCoeff;
26019             if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
26020                 y /= Math.max(1, coeff * pixelDistances[0]);
26021             }
26022             if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
26023                 x /= Math.max(1, coeff * pixelDistances[1]);
26024             }
26025             if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
26026                 y /= Math.max(1, coeff * pixelDistances[2]);
26027             }
26028             if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
26029                 x /= Math.max(1, coeff * pixelDistances[3]);
26030             }
26031             return [x, y];
26032         })
26033             .share();
26034         this._rotateBasicWithoutInertiaSubscription = basicRotation$
26035             .subscribe(function (basicRotation) {
26036             _this._navigator.stateService.rotateBasicWithoutInertia(basicRotation);
26037         });
26038         this._rotateBasicSubscription = basicRotation$
26039             .scan(function (rotationBuffer, rotation) {
26040             _this._drainBuffer(rotationBuffer);
26041             rotationBuffer.push([Date.now(), rotation]);
26042             return rotationBuffer;
26043         }, [])
26044             .sample(Observable_1.Observable
26045             .merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$))
26046             .map(function (rotationBuffer) {
26047             var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
26048             var basicRotation = [0, 0];
26049             for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
26050                 var rotation = drainedBuffer_1[_i];
26051                 basicRotation[0] += rotation[1][0];
26052                 basicRotation[1] += rotation[1][1];
26053             }
26054             var count = drainedBuffer.length;
26055             if (count > 0) {
26056                 basicRotation[0] /= count;
26057                 basicRotation[1] /= count;
26058             }
26059             return basicRotation;
26060         })
26061             .subscribe(function (basicRotation) {
26062             _this._navigator.stateService.rotateBasic(basicRotation);
26063         });
26064     };
26065     DragPanHandler.prototype._disable = function () {
26066         this._activeMouseSubscription.unsubscribe();
26067         this._activeTouchSubscription.unsubscribe();
26068         this._preventDefaultSubscription.unsubscribe();
26069         this._rotateBasicSubscription.unsubscribe();
26070         this._rotateBasicWithoutInertiaSubscription.unsubscribe();
26071         this._activeMouseSubscription = null;
26072         this._activeTouchSubscription = null;
26073         this._preventDefaultSubscription = null;
26074         this._rotateBasicSubscription = null;
26075     };
26076     DragPanHandler.prototype._getConfiguration = function (enable) {
26077         return { dragPan: enable };
26078     };
26079     DragPanHandler.prototype._drainBuffer = function (buffer) {
26080         var cutoff = 50;
26081         var now = Date.now();
26082         while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
26083             buffer.shift();
26084         }
26085         return buffer;
26086     };
26087     return DragPanHandler;
26088 }(Component_1.HandlerBase));
26089 exports.DragPanHandler = DragPanHandler;
26090 exports.default = DragPanHandler;
26091
26092 },{"../../Component":230,"rxjs/Observable":29,"rxjs/add/operator/concat":54,"rxjs/add/operator/sample":73,"rxjs/add/operator/takeWhile":83,"three":180}],282:[function(require,module,exports){
26093 "use strict";
26094 var __extends = (this && this.__extends) || (function () {
26095     var extendStatics = Object.setPrototypeOf ||
26096         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26097         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26098     return function (d, b) {
26099         extendStatics(d, b);
26100         function __() { this.constructor = d; }
26101         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26102     };
26103 })();
26104 Object.defineProperty(exports, "__esModule", { value: true });
26105 require("rxjs/add/observable/merge");
26106 require("rxjs/add/operator/filter");
26107 require("rxjs/add/operator/map");
26108 require("rxjs/add/operator/withLatestFrom");
26109 var Component_1 = require("../../Component");
26110 var Geo_1 = require("../../Geo");
26111 /**
26112  * @class MouseComponent
26113  *
26114  * @classdesc Component handling mouse and touch events for camera movement.
26115  */
26116 var MouseComponent = (function (_super) {
26117     __extends(MouseComponent, _super);
26118     function MouseComponent(name, container, navigator) {
26119         var _this = _super.call(this, name, container, navigator) || this;
26120         var spatial = new Geo_1.Spatial();
26121         var viewportCoords = new Geo_1.ViewportCoords();
26122         _this._spatial = spatial;
26123         _this._viewportCoords = viewportCoords;
26124         _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
26125         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
26126         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
26127         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
26128         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
26129         return _this;
26130     }
26131     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
26132         /**
26133          * Get double click zoom.
26134          *
26135          * @returns {DoubleClickZoomHandler} The double click zoom handler.
26136          */
26137         get: function () {
26138             return this._doubleClickZoomHandler;
26139         },
26140         enumerable: true,
26141         configurable: true
26142     });
26143     Object.defineProperty(MouseComponent.prototype, "dragPan", {
26144         /**
26145          * Get drag pan.
26146          *
26147          * @returns {DragPanHandler} The drag pan handler.
26148          */
26149         get: function () {
26150             return this._dragPanHandler;
26151         },
26152         enumerable: true,
26153         configurable: true
26154     });
26155     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
26156         /**
26157          * Get scroll zoom.
26158          *
26159          * @returns {ScrollZoomHandler} The scroll zoom handler.
26160          */
26161         get: function () {
26162             return this._scrollZoomHandler;
26163         },
26164         enumerable: true,
26165         configurable: true
26166     });
26167     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
26168         /**
26169          * Get touch zoom.
26170          *
26171          * @returns {TouchZoomHandler} The touch zoom handler.
26172          */
26173         get: function () {
26174             return this._touchZoomHandler;
26175         },
26176         enumerable: true,
26177         configurable: true
26178     });
26179     MouseComponent.prototype._activate = function () {
26180         var _this = this;
26181         this._bounceHandler.enable();
26182         this._configurationSubscription = this._configuration$
26183             .subscribe(function (configuration) {
26184             if (configuration.doubleClickZoom) {
26185                 _this._doubleClickZoomHandler.enable();
26186             }
26187             else {
26188                 _this._doubleClickZoomHandler.disable();
26189             }
26190             if (configuration.dragPan) {
26191                 _this._dragPanHandler.enable();
26192             }
26193             else {
26194                 _this._dragPanHandler.disable();
26195             }
26196             if (configuration.scrollZoom) {
26197                 _this._scrollZoomHandler.enable();
26198             }
26199             else {
26200                 _this._scrollZoomHandler.disable();
26201             }
26202             if (configuration.touchZoom) {
26203                 _this._touchZoomHandler.enable();
26204             }
26205             else {
26206                 _this._touchZoomHandler.disable();
26207             }
26208         });
26209         this._container.mouseService.claimMouse(this._name, 0);
26210     };
26211     MouseComponent.prototype._deactivate = function () {
26212         this._container.mouseService.unclaimMouse(this._name);
26213         this._configurationSubscription.unsubscribe();
26214         this._bounceHandler.disable();
26215         this._doubleClickZoomHandler.disable();
26216         this._dragPanHandler.disable();
26217         this._scrollZoomHandler.disable();
26218         this._touchZoomHandler.disable();
26219     };
26220     MouseComponent.prototype._getDefaultConfiguration = function () {
26221         return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
26222     };
26223     /** @inheritdoc */
26224     MouseComponent.componentName = "mouse";
26225     return MouseComponent;
26226 }(Component_1.Component));
26227 exports.MouseComponent = MouseComponent;
26228 Component_1.ComponentService.register(MouseComponent);
26229 exports.default = MouseComponent;
26230
26231 },{"../../Component":230,"../../Geo":233,"rxjs/add/observable/merge":44,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":85}],283:[function(require,module,exports){
26232 "use strict";
26233 var __extends = (this && this.__extends) || (function () {
26234     var extendStatics = Object.setPrototypeOf ||
26235         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26236         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26237     return function (d, b) {
26238         extendStatics(d, b);
26239         function __() { this.constructor = d; }
26240         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26241     };
26242 })();
26243 Object.defineProperty(exports, "__esModule", { value: true });
26244 var Component_1 = require("../../Component");
26245 /**
26246  * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
26247  *
26248  * @example
26249  * ```
26250  * var mouseComponent = viewer.getComponent("mouse");
26251  *
26252  * mouseComponent.scrollZoom.disable();
26253  * mouseComponent.scrollZoom.enable();
26254  *
26255  * var isEnabled = mouseComponent.scrollZoom.isEnabled;
26256  * ```
26257  */
26258 var ScrollZoomHandler = (function (_super) {
26259     __extends(ScrollZoomHandler, _super);
26260     function ScrollZoomHandler(component, container, navigator, viewportCoords) {
26261         var _this = _super.call(this, component, container, navigator) || this;
26262         _this._viewportCoords = viewportCoords;
26263         return _this;
26264     }
26265     ScrollZoomHandler.prototype._enable = function () {
26266         var _this = this;
26267         this._container.mouseService.claimWheel(this._component.name, 0);
26268         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
26269             .subscribe(function (event) {
26270             event.preventDefault();
26271         });
26272         this._zoomSubscription = this._container.mouseService
26273             .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$)
26274             .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
26275             return [w, f];
26276         })
26277             .filter(function (args) {
26278             var state = args[1].state;
26279             return state.currentNode.fullPano || state.nodesAhead < 1;
26280         })
26281             .map(function (args) {
26282             return args[0];
26283         })
26284             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
26285             return [w, r, t];
26286         })
26287             .subscribe(function (args) {
26288             var event = args[0];
26289             var render = args[1];
26290             var transform = args[2];
26291             var element = _this._container.element;
26292             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
26293             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26294             var reference = transform.projectBasic(unprojected.toArray());
26295             var deltaY = event.deltaY;
26296             if (event.deltaMode === 1) {
26297                 deltaY = 40 * deltaY;
26298             }
26299             else if (event.deltaMode === 2) {
26300                 deltaY = 800 * deltaY;
26301             }
26302             var canvasSize = _this._viewportCoords.containerToCanvas(element);
26303             var zoom = -3 * deltaY / canvasSize[1];
26304             _this._navigator.stateService.zoomIn(zoom, reference);
26305         });
26306     };
26307     ScrollZoomHandler.prototype._disable = function () {
26308         this._container.mouseService.unclaimWheel(this._component.name);
26309         this._preventDefaultSubscription.unsubscribe();
26310         this._zoomSubscription.unsubscribe();
26311         this._preventDefaultSubscription = null;
26312         this._zoomSubscription = null;
26313     };
26314     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
26315         return { scrollZoom: enable };
26316     };
26317     return ScrollZoomHandler;
26318 }(Component_1.HandlerBase));
26319 exports.ScrollZoomHandler = ScrollZoomHandler;
26320 exports.default = ScrollZoomHandler;
26321
26322 },{"../../Component":230}],284:[function(require,module,exports){
26323 "use strict";
26324 /// <reference path="../../../typings/index.d.ts" />
26325 var __extends = (this && this.__extends) || (function () {
26326     var extendStatics = Object.setPrototypeOf ||
26327         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26328         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26329     return function (d, b) {
26330         extendStatics(d, b);
26331         function __() { this.constructor = d; }
26332         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26333     };
26334 })();
26335 Object.defineProperty(exports, "__esModule", { value: true });
26336 var Observable_1 = require("rxjs/Observable");
26337 var Component_1 = require("../../Component");
26338 /**
26339  * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
26340  *
26341  * @example
26342  * ```
26343  * var mouseComponent = viewer.getComponent("mouse");
26344  *
26345  * mouseComponent.touchZoom.disable();
26346  * mouseComponent.touchZoom.enable();
26347  *
26348  * var isEnabled = mouseComponent.touchZoom.isEnabled;
26349  * ```
26350  */
26351 var TouchZoomHandler = (function (_super) {
26352     __extends(TouchZoomHandler, _super);
26353     function TouchZoomHandler(component, container, navigator, viewportCoords) {
26354         var _this = _super.call(this, component, container, navigator) || this;
26355         _this._viewportCoords = viewportCoords;
26356         return _this;
26357     }
26358     TouchZoomHandler.prototype._enable = function () {
26359         var _this = this;
26360         this._preventDefaultSubscription = this._container.touchService.pinch$
26361             .subscribe(function (pinch) {
26362             pinch.originalEvent.preventDefault();
26363         });
26364         var pinchStarted$ = this._container.touchService.pinchStart$
26365             .map(function (event) {
26366             return true;
26367         });
26368         var pinchStopped$ = this._container.touchService.pinchEnd$
26369             .map(function (event) {
26370             return false;
26371         });
26372         this._activeSubscription = Observable_1.Observable
26373             .merge(pinchStarted$, pinchStopped$)
26374             .subscribe(this._container.touchService.activate$);
26375         this._zoomSubscription = this._container.touchService.pinch$
26376             .withLatestFrom(this._navigator.stateService.currentState$)
26377             .filter(function (args) {
26378             var state = args[1].state;
26379             return state.currentNode.fullPano || state.nodesAhead < 1;
26380         })
26381             .map(function (args) {
26382             return args[0];
26383         })
26384             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
26385             .subscribe(function (_a) {
26386             var pinch = _a[0], render = _a[1], transform = _a[2];
26387             var element = _this._container.element;
26388             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
26389             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26390             var reference = transform.projectBasic(unprojected.toArray());
26391             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
26392             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
26393             _this._navigator.stateService.zoomIn(zoom, reference);
26394         });
26395     };
26396     TouchZoomHandler.prototype._disable = function () {
26397         this._activeSubscription.unsubscribe();
26398         this._preventDefaultSubscription.unsubscribe();
26399         this._zoomSubscription.unsubscribe();
26400         this._preventDefaultSubscription = null;
26401         this._zoomSubscription = null;
26402     };
26403     TouchZoomHandler.prototype._getConfiguration = function (enable) {
26404         return { touchZoom: enable };
26405     };
26406     return TouchZoomHandler;
26407 }(Component_1.HandlerBase));
26408 exports.TouchZoomHandler = TouchZoomHandler;
26409 exports.default = TouchZoomHandler;
26410
26411 },{"../../Component":230,"rxjs/Observable":29}],285:[function(require,module,exports){
26412 "use strict";
26413 Object.defineProperty(exports, "__esModule", { value: true });
26414 var Popup_1 = require("./popup/Popup");
26415 exports.Popup = Popup_1.Popup;
26416 var PopupComponent_1 = require("./PopupComponent");
26417 exports.PopupComponent = PopupComponent_1.PopupComponent;
26418
26419 },{"./PopupComponent":286,"./popup/Popup":287}],286:[function(require,module,exports){
26420 "use strict";
26421 var __extends = (this && this.__extends) || (function () {
26422     var extendStatics = Object.setPrototypeOf ||
26423         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26424         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26425     return function (d, b) {
26426         extendStatics(d, b);
26427         function __() { this.constructor = d; }
26428         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26429     };
26430 })();
26431 Object.defineProperty(exports, "__esModule", { value: true });
26432 var Observable_1 = require("rxjs/Observable");
26433 var Subject_1 = require("rxjs/Subject");
26434 var Component_1 = require("../../Component");
26435 var Utils_1 = require("../../Utils");
26436 /**
26437  * @class PopupComponent
26438  *
26439  * @classdesc Component for showing HTML popup objects.
26440  *
26441  * The `add` method is used for adding new popups. Popups are removed by reference.
26442  *
26443  * It is not possible to update popups in the set by updating any properties
26444  * directly on the popup object. Popups need to be replaced by
26445  * removing them and creating new ones with relevant changed properties and
26446  * adding those instead.
26447  *
26448  * Popups are only relevant to a single image because they are based on
26449  * 2D basic image coordinates. Popups related to a certain image should
26450  * be removed when the viewer is moved to another node.
26451  *
26452  * To retrive and use the popup component
26453  *
26454  * @example
26455  * ```
26456  * var viewer = new Mapillary.Viewer(
26457  *     "<element-id>",
26458  *     "<client-id>",
26459  *     "<my key>",
26460  *     { component: { popup: true } });
26461  *
26462  * var popupComponent = viewer.getComponent("popup");
26463  * ```
26464  */
26465 var PopupComponent = (function (_super) {
26466     __extends(PopupComponent, _super);
26467     function PopupComponent(name, container, navigator, dom) {
26468         var _this = _super.call(this, name, container, navigator) || this;
26469         _this._dom = !!dom ? dom : new Utils_1.DOM();
26470         _this._popups = [];
26471         _this._added$ = new Subject_1.Subject();
26472         _this._popups$ = new Subject_1.Subject();
26473         return _this;
26474     }
26475     /**
26476      * Add popups to the popups set.
26477      *
26478      * @description Adding a new popup never replaces an old one
26479      * because they are stored by reference. Adding an already
26480      * existing popup has no effect.
26481      *
26482      * @param {Array<Popup>} popups - Popups to add.
26483      *
26484      * @example ```popupComponent.add([popup1, popup2]);```
26485      */
26486     PopupComponent.prototype.add = function (popups) {
26487         for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
26488             var popup = popups_1[_i];
26489             if (this._popups.indexOf(popup) !== -1) {
26490                 continue;
26491             }
26492             this._popups.push(popup);
26493             if (this._activated) {
26494                 popup.setParentContainer(this._popupContainer);
26495             }
26496         }
26497         this._added$.next(popups);
26498         this._popups$.next(this._popups);
26499     };
26500     /**
26501      * Returns an array of all popups.
26502      *
26503      * @example ```var popups = popupComponent.getAll();```
26504      */
26505     PopupComponent.prototype.getAll = function () {
26506         return this._popups.slice();
26507     };
26508     /**
26509      * Remove popups based on reference from the popup set.
26510      *
26511      * @param {Array<Popup>} popups - Popups to remove.
26512      *
26513      * @example ```popupComponent.remove([popup1, popup2]);```
26514      */
26515     PopupComponent.prototype.remove = function (popups) {
26516         for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
26517             var popup = popups_2[_i];
26518             this._remove(popup);
26519         }
26520         this._popups$.next(this._popups);
26521     };
26522     /**
26523      * Remove all popups from the popup set.
26524      *
26525      * @example ```popupComponent.removeAll();```
26526      */
26527     PopupComponent.prototype.removeAll = function () {
26528         for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
26529             var popup = _a[_i];
26530             this._remove(popup);
26531         }
26532         this._popups$.next(this._popups);
26533     };
26534     PopupComponent.prototype._activate = function () {
26535         var _this = this;
26536         this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
26537         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26538             var popup = _a[_i];
26539             popup.setParentContainer(this._popupContainer);
26540         }
26541         this._updateAllSubscription = Observable_1.Observable
26542             .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
26543             .subscribe(function (_a) {
26544             var renderCamera = _a[0], size = _a[1], transform = _a[2];
26545             for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
26546                 var popup = _b[_i];
26547                 popup.update(renderCamera, size, transform);
26548             }
26549         });
26550         var changed$ = this._popups$
26551             .startWith(this._popups)
26552             .switchMap(function (popups) {
26553             return Observable_1.Observable
26554                 .from(popups)
26555                 .mergeMap(function (popup) {
26556                 return popup.changed$;
26557             });
26558         })
26559             .map(function (popup) {
26560             return [popup];
26561         });
26562         this._updateAddedChangedSubscription = this._added$
26563             .merge(changed$)
26564             .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
26565             .subscribe(function (_a) {
26566             var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
26567             for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
26568                 var popup = popups_3[_i];
26569                 popup.update(renderCamera, size, transform);
26570             }
26571         });
26572     };
26573     PopupComponent.prototype._deactivate = function () {
26574         this._updateAllSubscription.unsubscribe();
26575         this._updateAddedChangedSubscription.unsubscribe();
26576         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26577             var popup = _a[_i];
26578             popup.remove();
26579         }
26580         this._container.element.removeChild(this._popupContainer);
26581         delete this._popupContainer;
26582     };
26583     PopupComponent.prototype._getDefaultConfiguration = function () {
26584         return {};
26585     };
26586     PopupComponent.prototype._remove = function (popup) {
26587         var index = this._popups.indexOf(popup);
26588         if (index === -1) {
26589             return;
26590         }
26591         var removed = this._popups.splice(index, 1)[0];
26592         if (this._activated) {
26593             removed.remove();
26594         }
26595     };
26596     PopupComponent.componentName = "popup";
26597     return PopupComponent;
26598 }(Component_1.Component));
26599 exports.PopupComponent = PopupComponent;
26600 Component_1.ComponentService.register(PopupComponent);
26601 exports.default = PopupComponent;
26602
26603 },{"../../Component":230,"../../Utils":240,"rxjs/Observable":29,"rxjs/Subject":34}],287:[function(require,module,exports){
26604 "use strict";
26605 /// <reference path="../../../../typings/index.d.ts" />
26606 Object.defineProperty(exports, "__esModule", { value: true });
26607 var Subject_1 = require("rxjs/Subject");
26608 var Geo_1 = require("../../../Geo");
26609 var Utils_1 = require("../../../Utils");
26610 var Viewer_1 = require("../../../Viewer");
26611 /**
26612  * @class Popup
26613  *
26614  * @classdesc Popup instance for rendering custom HTML content
26615  * on top of images. Popups are based on 2D basic image coordinates
26616  * (see the {@link Viewer} class documentation for more information about coordinate
26617  * systems) and a certain popup is therefore only relevant to a single image.
26618  * Popups related to a certain image should be removed when moving
26619  * to another image.
26620  *
26621  * A popup must have both its content and its point or rect set to be
26622  * rendered. Popup options can not be updated after creation but the
26623  * basic point or rect as well as its content can be changed by calling
26624  * the appropriate methods.
26625  *
26626  * To create and add one `Popup` with default configuration
26627  * (tooltip visuals and automatic float) and one with specific options
26628  * use
26629  *
26630  * @example
26631  * ```
26632  * var defaultSpan = document.createElement('span');
26633  * defaultSpan.innerHTML = 'hello default';
26634  *
26635  * var defaultPopup = new Mapillary.PopupComponent.Popup();
26636  * defaultPopup.setDOMContent(defaultSpan);
26637  * defaultPopup.setBasicPoint([0.3, 0.3]);
26638  *
26639  * var cleanSpan = document.createElement('span');
26640  * cleanSpan.innerHTML = 'hello clean';
26641  *
26642  * var cleanPopup = new Mapillary.PopupComponent.Popup({
26643  *     clean: true,
26644  *     float: Mapillary.Alignment.Top,
26645  *     offset: 10,
26646  *     opacity: 0.7,
26647  * });
26648  *
26649  * cleanPopup.setDOMContent(cleanSpan);
26650  * cleanPopup.setBasicPoint([0.6, 0.6]);
26651  *
26652  * popupComponent.add([defaultPopup, cleanPopup]);
26653  * ```
26654  *
26655  * @description Implementation of API methods and API documentation inspired
26656  * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
26657  */
26658 var Popup = (function () {
26659     function Popup(options, viewportCoords, dom) {
26660         this._options = {};
26661         if (!!options) {
26662             this._options.capturePointer = options.capturePointer == null ? true : options.capturePointer;
26663             this._options.clean = options.clean;
26664             this._options.float = options.float;
26665             this._options.offset = options.offset;
26666             this._options.opacity = options.opacity;
26667             this._options.position = options.position;
26668         }
26669         this._dom = !!dom ? dom : new Utils_1.DOM();
26670         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
26671         this._notifyChanged$ = new Subject_1.Subject();
26672     }
26673     Object.defineProperty(Popup.prototype, "changed$", {
26674         /**
26675          * @ignore
26676          *
26677          * @description Internal observable used by the component to
26678          * render the popup when its position or content has changed.
26679          */
26680         get: function () {
26681             return this._notifyChanged$;
26682         },
26683         enumerable: true,
26684         configurable: true
26685     });
26686     /**
26687      * @ignore
26688      *
26689      * @description Internal method used by the component to
26690      * remove all references to the popup.
26691      */
26692     Popup.prototype.remove = function () {
26693         if (this._content && this._content.parentNode) {
26694             this._content.parentNode.removeChild(this._content);
26695         }
26696         if (this._container) {
26697             this._container.parentNode.removeChild(this._container);
26698             delete this._container;
26699         }
26700         if (this._parentContainer) {
26701             delete this._parentContainer;
26702         }
26703     };
26704     /**
26705      * Sets a 2D basic image coordinates point to the popup's anchor, and
26706      * moves the popup to it.
26707      *
26708      * @description Overwrites any previously set point or rect.
26709      *
26710      * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
26711      *
26712      * @example
26713      * ```
26714      * var popup = new Mapillary.PopupComponent.Popup();
26715      * popup.setText('hello image');
26716      * popup.setBasicPoint([0.3, 0.3]);
26717      *
26718      * popupComponent.add([popup]);
26719      * ```
26720      */
26721     Popup.prototype.setBasicPoint = function (basicPoint) {
26722         this._point = basicPoint.slice();
26723         this._rect = null;
26724         this._notifyChanged$.next(this);
26725     };
26726     /**
26727      * Sets a 2D basic image coordinates rect to the popup's anchor, and
26728      * moves the popup to it.
26729      *
26730      * @description Overwrites any previously set point or rect.
26731      *
26732      * @param {Array<number>} basicRect - Rect in 2D basic image
26733      * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
26734      *
26735      * @example
26736      * ```
26737      * var popup = new Mapillary.PopupComponent.Popup();
26738      * popup.setText('hello image');
26739      * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
26740      *
26741      * popupComponent.add([popup]);
26742      * ```
26743      */
26744     Popup.prototype.setBasicRect = function (basicRect) {
26745         this._rect = basicRect.slice();
26746         this._point = null;
26747         this._notifyChanged$.next(this);
26748     };
26749     /**
26750      * Sets the popup's content to the element provided as a DOM node.
26751      *
26752      * @param {Node} htmlNode - A DOM node to be used as content for the popup.
26753      *
26754      * @example
26755      * ```
26756      * var div = document.createElement('div');
26757      * div.innerHTML = 'hello image';
26758      *
26759      * var popup = new Mapillary.PopupComponent.Popup();
26760      * popup.setDOMContent(div);
26761      * popup.setBasicPoint([0.3, 0.3]);
26762      *
26763      * popupComponent.add([popup]);
26764      * ```
26765      */
26766     Popup.prototype.setDOMContent = function (htmlNode) {
26767         if (this._content && this._content.parentNode) {
26768             this._content.parentNode.removeChild(this._content);
26769         }
26770         var className = "mapillaryjs-popup-content" +
26771             (this._options.clean === true ? "-clean" : "") +
26772             (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
26773         this._content = this._dom.createElement("div", className, this._container);
26774         this._content.appendChild(htmlNode);
26775         this._notifyChanged$.next(this);
26776     };
26777     /**
26778      * Sets the popup's content to the HTML provided as a string.
26779      *
26780      * @description This method does not perform HTML filtering or sanitization,
26781      * and must be used only with trusted content. Consider Popup#setText if the
26782      * content is an untrusted text string.
26783      *
26784      * @param {string} html - A string representing HTML content for the popup.
26785      *
26786      * @example
26787      * ```
26788      * var popup = new Mapillary.PopupComponent.Popup();
26789      * popup.setHTML('<div>hello image</div>');
26790      * popup.setBasicPoint([0.3, 0.3]);
26791      *
26792      * popupComponent.add([popup]);
26793      * ```
26794      */
26795     Popup.prototype.setHTML = function (html) {
26796         var frag = this._dom.document.createDocumentFragment();
26797         var temp = this._dom.createElement("body");
26798         var child;
26799         temp.innerHTML = html;
26800         while (true) {
26801             child = temp.firstChild;
26802             if (!child) {
26803                 break;
26804             }
26805             frag.appendChild(child);
26806         }
26807         this.setDOMContent(frag);
26808     };
26809     /**
26810      * Sets the popup's content to a string of text.
26811      *
26812      * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
26813      * Use this method for security against XSS if the popup content is user-provided.
26814      *
26815      * @param {string} text - Textual content for the popup.
26816      *
26817      * @example
26818      * ```
26819      * var popup = new Mapillary.PopupComponent.Popup();
26820      * popup.setText('hello image');
26821      * popup.setBasicPoint([0.3, 0.3]);
26822      *
26823      * popupComponent.add([popup]);
26824      * ```
26825      */
26826     Popup.prototype.setText = function (text) {
26827         this.setDOMContent(this._dom.document.createTextNode(text));
26828     };
26829     /**
26830      * @ignore
26831      *
26832      * @description Internal method for attaching the popup to
26833      * its parent container so that it is rendered in the DOM tree.
26834      */
26835     Popup.prototype.setParentContainer = function (parentContainer) {
26836         this._parentContainer = parentContainer;
26837     };
26838     /**
26839      * @ignore
26840      *
26841      * @description Internal method for updating the rendered
26842      * position of the popup called by the popup component.
26843      */
26844     Popup.prototype.update = function (renderCamera, size, transform) {
26845         if (!this._parentContainer || !this._content) {
26846             return;
26847         }
26848         if (!this._point && !this._rect) {
26849             return;
26850         }
26851         if (!this._container) {
26852             this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
26853             var showTip = this._options.clean !== true &&
26854                 this._options.float !== Viewer_1.Alignment.Center;
26855             if (showTip) {
26856                 var tipClassName = "mapillaryjs-popup-tip" +
26857                     (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
26858                 this._tip = this._dom.createElement("div", tipClassName, this._container);
26859                 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
26860             }
26861             this._container.appendChild(this._content);
26862             this._parentContainer.appendChild(this._container);
26863             if (this._options.opacity != null) {
26864                 this._container.style.opacity = this._options.opacity.toString();
26865             }
26866         }
26867         var pointPixel = null;
26868         var position = this._alignmentToPopupAligment(this._options.position);
26869         var float = this._alignmentToPopupAligment(this._options.float);
26870         if (this._point != null) {
26871             pointPixel =
26872                 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26873         }
26874         else {
26875             var classList_1 = this._container.classList;
26876             var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
26877             var appliedPosition = null;
26878             for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
26879                 var alignment = alignments_1[_i];
26880                 if (classList_1.contains("mapillaryjs-popup-float-" + alignment)) {
26881                     appliedPosition = alignment;
26882                     break;
26883                 }
26884             }
26885             _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
26886             if (!float) {
26887                 float = position;
26888             }
26889         }
26890         if (pointPixel == null) {
26891             this._container.style.visibility = "hidden";
26892             return;
26893         }
26894         this._container.style.visibility = "visible";
26895         if (!float) {
26896             var width = this._container.offsetWidth;
26897             var height = this._container.offsetHeight;
26898             var floats = this._pixelToFloats(pointPixel, size, width, height);
26899             float = floats.length === 0 ? "top" : floats.join("-");
26900         }
26901         var offset = this._normalizeOffset(this._options.offset);
26902         pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
26903         pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
26904         var floatTranslate = {
26905             "bottom": "translate(-50%,0)",
26906             "bottom-left": "translate(-100%,0)",
26907             "bottom-right": "translate(0,0)",
26908             "center": "translate(-50%,-50%)",
26909             "left": "translate(-100%,-50%)",
26910             "right": "translate(0,-50%)",
26911             "top": "translate(-50%,-100%)",
26912             "top-left": "translate(-100%,-100%)",
26913             "top-right": "translate(0,-100%)",
26914         };
26915         var classList = this._container.classList;
26916         for (var key in floatTranslate) {
26917             if (!floatTranslate.hasOwnProperty(key)) {
26918                 continue;
26919             }
26920             classList.remove("mapillaryjs-popup-float-" + key);
26921         }
26922         classList.add("mapillaryjs-popup-float-" + float);
26923         this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
26924         var _a;
26925     };
26926     Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
26927         if (!position) {
26928             var width = this._container.offsetWidth;
26929             var height = this._container.offsetHeight;
26930             var floatOffsets = {
26931                 "bottom": [0, height / 2],
26932                 "bottom-left": [-width / 2, height / 2],
26933                 "bottom-right": [width / 2, height / 2],
26934                 "left": [-width / 2, 0],
26935                 "right": [width / 2, 0],
26936                 "top": [0, -height / 2],
26937                 "top-left": [-width / 2, -height / 2],
26938                 "top-right": [width / 2, -height / 2],
26939             };
26940             var automaticPositions = ["top", "bottom", "left", "right"];
26941             var largestVisibleArea = [0, null, null];
26942             for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
26943                 var automaticPosition = automaticPositions_1[_i];
26944                 var pointBasic_1 = this._pointFromRectPosition(rect, automaticPosition);
26945                 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic_1[0], pointBasic_1[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26946                 if (pointPixel == null) {
26947                     continue;
26948                 }
26949                 var floatOffset = floatOffsets[automaticPosition];
26950                 var offsetedPosition = [pointPixel[0] + floatOffset[0], pointPixel[1] + floatOffset[1]];
26951                 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
26952                 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
26953                 if (floats.length === 0 &&
26954                     pointPixel[0] > 0 &&
26955                     pointPixel[0] < size.width &&
26956                     pointPixel[1] > 0 &&
26957                     pointPixel[1] < size.height) {
26958                     return [pointPixel, automaticPosition];
26959                 }
26960                 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
26961                 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
26962                 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
26963                 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
26964                 var visibleX = Math.max(0, maxX - minX);
26965                 var visibleY = Math.max(0, maxY - minY);
26966                 var visibleArea = staticCoeff * visibleX * visibleY;
26967                 if (visibleArea > largestVisibleArea[0]) {
26968                     largestVisibleArea[0] = visibleArea;
26969                     largestVisibleArea[1] = pointPixel;
26970                     largestVisibleArea[2] = automaticPosition;
26971                 }
26972             }
26973             if (largestVisibleArea[0] > 0) {
26974                 return [largestVisibleArea[1], largestVisibleArea[2]];
26975             }
26976         }
26977         var pointBasic = this._pointFromRectPosition(rect, position);
26978         var pointCanvas = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26979         return [pointCanvas, position != null ? position : "top"];
26980     };
26981     Popup.prototype._alignmentToPopupAligment = function (float) {
26982         switch (float) {
26983             case Viewer_1.Alignment.Bottom:
26984                 return "bottom";
26985             case Viewer_1.Alignment.BottomLeft:
26986                 return "bottom-left";
26987             case Viewer_1.Alignment.BottomRight:
26988                 return "bottom-right";
26989             case Viewer_1.Alignment.Center:
26990                 return "center";
26991             case Viewer_1.Alignment.Left:
26992                 return "left";
26993             case Viewer_1.Alignment.Right:
26994                 return "right";
26995             case Viewer_1.Alignment.Top:
26996                 return "top";
26997             case Viewer_1.Alignment.TopLeft:
26998                 return "top-left";
26999             case Viewer_1.Alignment.TopRight:
27000                 return "top-right";
27001             default:
27002                 return null;
27003         }
27004     };
27005     Popup.prototype._normalizeOffset = function (offset) {
27006         if (offset == null) {
27007             return this._normalizeOffset(0);
27008         }
27009         if (typeof offset === "number") {
27010             // input specifies a radius
27011             var sideOffset = offset;
27012             var sign = sideOffset >= 0 ? 1 : -1;
27013             var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
27014             return {
27015                 "bottom": [0, sideOffset],
27016                 "bottom-left": [-cornerOffset, cornerOffset],
27017                 "bottom-right": [cornerOffset, cornerOffset],
27018                 "center": [0, 0],
27019                 "left": [-sideOffset, 0],
27020                 "right": [sideOffset, 0],
27021                 "top": [0, -sideOffset],
27022                 "top-left": [-cornerOffset, -cornerOffset],
27023                 "top-right": [cornerOffset, -cornerOffset],
27024             };
27025         }
27026         else {
27027             // input specifes a value for each position
27028             return {
27029                 "bottom": offset.bottom || [0, 0],
27030                 "bottom-left": offset.bottomLeft || [0, 0],
27031                 "bottom-right": offset.bottomRight || [0, 0],
27032                 "center": offset.center || [0, 0],
27033                 "left": offset.left || [0, 0],
27034                 "right": offset.right || [0, 0],
27035                 "top": offset.top || [0, 0],
27036                 "top-left": offset.topLeft || [0, 0],
27037                 "top-right": offset.topRight || [0, 0],
27038             };
27039         }
27040     };
27041     Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
27042         var floats = [];
27043         if (pointPixel[1] < height) {
27044             floats.push("bottom");
27045         }
27046         else if (pointPixel[1] > size.height - height) {
27047             floats.push("top");
27048         }
27049         if (pointPixel[0] < width / 2) {
27050             floats.push("right");
27051         }
27052         else if (pointPixel[0] > size.width - width / 2) {
27053             floats.push("left");
27054         }
27055         return floats;
27056     };
27057     Popup.prototype._pointFromRectPosition = function (rect, position) {
27058         switch (position) {
27059             case "bottom":
27060                 return [(rect[0] + rect[2]) / 2, rect[3]];
27061             case "bottom-left":
27062                 return [rect[0], rect[3]];
27063             case "bottom-right":
27064                 return [rect[2], rect[3]];
27065             case "center":
27066                 return [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2];
27067             case "left":
27068                 return [rect[0], (rect[1] + rect[3]) / 2];
27069             case "right":
27070                 return [rect[2], (rect[1] + rect[3]) / 2];
27071             case "top":
27072                 return [(rect[0] + rect[2]) / 2, rect[1]];
27073             case "top-left":
27074                 return [rect[0], rect[1]];
27075             case "top-right":
27076                 return [rect[2], rect[1]];
27077             default:
27078                 return [(rect[0] + rect[2]) / 2, rect[3]];
27079         }
27080     };
27081     return Popup;
27082 }());
27083 exports.Popup = Popup;
27084 exports.default = Popup;
27085
27086 },{"../../../Geo":233,"../../../Utils":240,"../../../Viewer":241,"rxjs/Subject":34}],288:[function(require,module,exports){
27087 "use strict";
27088 /// <reference path="../../../typings/index.d.ts" />
27089 var __extends = (this && this.__extends) || (function () {
27090     var extendStatics = Object.setPrototypeOf ||
27091         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27092         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27093     return function (d, b) {
27094         extendStatics(d, b);
27095         function __() { this.constructor = d; }
27096         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27097     };
27098 })();
27099 Object.defineProperty(exports, "__esModule", { value: true });
27100 var Observable_1 = require("rxjs/Observable");
27101 var Subject_1 = require("rxjs/Subject");
27102 require("rxjs/add/observable/combineLatest");
27103 require("rxjs/add/observable/of");
27104 require("rxjs/add/operator/bufferCount");
27105 require("rxjs/add/operator/concat");
27106 require("rxjs/add/operator/distinctUntilChanged");
27107 require("rxjs/add/operator/filter");
27108 require("rxjs/add/operator/finally");
27109 require("rxjs/add/operator/first");
27110 require("rxjs/add/operator/map");
27111 require("rxjs/add/operator/publishReplay");
27112 require("rxjs/add/operator/scan");
27113 require("rxjs/add/operator/share");
27114 require("rxjs/add/operator/switchMap");
27115 require("rxjs/add/operator/takeUntil");
27116 require("rxjs/add/operator/withLatestFrom");
27117 var Component_1 = require("../../Component");
27118 var Edge_1 = require("../../Edge");
27119 /**
27120  * @class SequenceComponent
27121  * @classdesc Component showing navigation arrows for sequence directions
27122  * as well as playing button. Exposes an API to start and stop play.
27123  */
27124 var SequenceComponent = (function (_super) {
27125     __extends(SequenceComponent, _super);
27126     function SequenceComponent(name, container, navigator) {
27127         var _this = _super.call(this, name, container, navigator) || this;
27128         _this._nodesAhead = 5;
27129         _this._configurationOperation$ = new Subject_1.Subject();
27130         _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
27131         _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
27132         _this._containerWidth$ = new Subject_1.Subject();
27133         _this._hoveredKeySubject$ = new Subject_1.Subject();
27134         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
27135         _this._edgeStatus$ = _this._navigator.stateService.currentNode$
27136             .switchMap(function (node) {
27137             return node.sequenceEdges$;
27138         })
27139             .publishReplay(1)
27140             .refCount();
27141         return _this;
27142     }
27143     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
27144         /**
27145          * Get hovered key observable.
27146          *
27147          * @description An observable emitting the key of the node for the direction
27148          * arrow that is being hovered. When the mouse leaves a direction arrow null
27149          * is emitted.
27150          *
27151          * @returns {Observable<string>}
27152          */
27153         get: function () {
27154             return this._hoveredKey$;
27155         },
27156         enumerable: true,
27157         configurable: true
27158     });
27159     /**
27160      * Start playing.
27161      *
27162      * @fires PlayerComponent#playingchanged
27163      */
27164     SequenceComponent.prototype.play = function () {
27165         this.configure({ playing: true });
27166     };
27167     /**
27168      * Stop playing.
27169      *
27170      * @fires PlayerComponent#playingchanged
27171      */
27172     SequenceComponent.prototype.stop = function () {
27173         this.configure({ playing: false });
27174     };
27175     /**
27176      * Set the direction to follow when playing.
27177      *
27178      * @param {EdgeDirection} direction - The direction that will be followed when playing.
27179      */
27180     SequenceComponent.prototype.setDirection = function (direction) {
27181         this.configure({ direction: direction });
27182     };
27183     /**
27184      * Set highlight key.
27185      *
27186      * @description The arrow pointing towards the node corresponding to the
27187      * highlight key will be highlighted.
27188      *
27189      * @param {string} highlightKey Key of node to be highlighted if existing.
27190      */
27191     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
27192         this.configure({ highlightKey: highlightKey });
27193     };
27194     /**
27195      * Set max width of container element.
27196      *
27197      * @description Set max width of the container element holding
27198      * the sequence navigation elements. If the min width is larger than the
27199      * max width the min width value will be used.
27200      *
27201      * The container element is automatically resized when the resize
27202      * method on the Viewer class is called.
27203      *
27204      * @param {number} minWidth
27205      */
27206     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
27207         this.configure({ maxWidth: maxWidth });
27208     };
27209     /**
27210      * Set min width of container element.
27211      *
27212      * @description Set min width of the container element holding
27213      * the sequence navigation elements. If the min width is larger than the
27214      * max width the min width value will be used.
27215      *
27216      * The container element is automatically resized when the resize
27217      * method on the Viewer class is called.
27218      *
27219      * @param {number} minWidth
27220      */
27221     SequenceComponent.prototype.setMinWidth = function (minWidth) {
27222         this.configure({ minWidth: minWidth });
27223     };
27224     /**
27225      * Set the value indicating whether the sequence UI elements should be visible.
27226      *
27227      * @param {boolean} visible
27228      */
27229     SequenceComponent.prototype.setVisible = function (visible) {
27230         this.configure({ visible: visible });
27231     };
27232     /** @inheritdoc */
27233     SequenceComponent.prototype.resize = function () {
27234         var _this = this;
27235         this._configuration$
27236             .first()
27237             .map(function (configuration) {
27238             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
27239         })
27240             .subscribe(function (containerWidth) {
27241             _this._containerWidth$.next(containerWidth);
27242         });
27243     };
27244     SequenceComponent.prototype._activate = function () {
27245         var _this = this;
27246         this._renderSubscription = Observable_1.Observable
27247             .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
27248             .map(function (ec) {
27249             var edgeStatus = ec[0];
27250             var configuration = ec[1];
27251             var containerWidth = ec[2];
27252             var vNode = _this._sequenceDOMRenderer
27253                 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
27254             return { name: _this._name, vnode: vNode };
27255         })
27256             .subscribe(this._container.domRenderer.render$);
27257         this._containerWidthSubscription = this._configuration$
27258             .distinctUntilChanged(function (value1, value2) {
27259             return value1[0] === value2[0] && value1[1] === value2[1];
27260         }, function (configuration) {
27261             return [configuration.minWidth, configuration.maxWidth];
27262         })
27263             .map(function (configuration) {
27264             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
27265         })
27266             .subscribe(this._containerWidth$);
27267         this._configurationSubscription = this._configurationOperation$
27268             .scan(function (configuration, operation) {
27269             return operation(configuration);
27270         }, { playing: false })
27271             .finally(function () {
27272             if (_this._playingSubscription != null) {
27273                 _this._navigator.stateService.cutNodes();
27274                 _this._stop();
27275             }
27276         })
27277             .subscribe(function () { });
27278         this._configuration$
27279             .map(function (newConfiguration) {
27280             return function (configuration) {
27281                 if (newConfiguration.playing !== configuration.playing) {
27282                     _this._navigator.stateService.cutNodes();
27283                     if (newConfiguration.playing) {
27284                         _this._play();
27285                     }
27286                     else {
27287                         _this._stop();
27288                     }
27289                 }
27290                 configuration.playing = newConfiguration.playing;
27291                 return configuration;
27292             };
27293         })
27294             .subscribe(this._configurationOperation$);
27295         this._stopSubscription = this._configuration$
27296             .switchMap(function (configuration) {
27297             var edgeStatus$ = configuration.playing ?
27298                 _this._edgeStatus$ :
27299                 Observable_1.Observable.empty();
27300             var edgeDirection$ = Observable_1.Observable
27301                 .of(configuration.direction);
27302             return Observable_1.Observable
27303                 .combineLatest(edgeStatus$, edgeDirection$);
27304         })
27305             .map(function (ne) {
27306             var edgeStatus = ne[0];
27307             var direction = ne[1];
27308             if (!edgeStatus.cached) {
27309                 return true;
27310             }
27311             for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27312                 var edge = _a[_i];
27313                 if (edge.data.direction === direction) {
27314                     return true;
27315                 }
27316             }
27317             return false;
27318         })
27319             .filter(function (hasEdge) {
27320             return !hasEdge;
27321         })
27322             .map(function (hasEdge) {
27323             return { playing: false };
27324         })
27325             .subscribe(this._configurationSubject$);
27326         this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
27327             .switchMap(function (direction) {
27328             return _this._edgeStatus$
27329                 .map(function (edgeStatus) {
27330                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27331                     var edge = _a[_i];
27332                     if (edge.data.direction === direction) {
27333                         return edge.to;
27334                     }
27335                 }
27336                 return null;
27337             })
27338                 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
27339                 .concat(Observable_1.Observable.of(null));
27340         })
27341             .distinctUntilChanged()
27342             .subscribe(this._hoveredKeySubject$);
27343     };
27344     SequenceComponent.prototype._deactivate = function () {
27345         this._stopSubscription.unsubscribe();
27346         this._renderSubscription.unsubscribe();
27347         this._configurationSubscription.unsubscribe();
27348         this._containerWidthSubscription.unsubscribe();
27349         this._hoveredKeySubscription.unsubscribe();
27350         this.stop();
27351     };
27352     SequenceComponent.prototype._getDefaultConfiguration = function () {
27353         return {
27354             direction: Edge_1.EdgeDirection.Next,
27355             maxWidth: 117,
27356             minWidth: 70,
27357             playing: false,
27358             visible: true,
27359         };
27360     };
27361     SequenceComponent.prototype._play = function () {
27362         var _this = this;
27363         this._playingSubscription = this._navigator.stateService.currentState$
27364             .filter(function (frame) {
27365             return frame.state.nodesAhead < _this._nodesAhead;
27366         })
27367             .map(function (frame) {
27368             return frame.state.lastNode;
27369         })
27370             .distinctUntilChanged(undefined, function (lastNode) {
27371             return lastNode.key;
27372         })
27373             .withLatestFrom(this._configuration$, function (lastNode, configuration) {
27374             return [lastNode, configuration.direction];
27375         })
27376             .switchMap(function (nd) {
27377             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
27378                 nd[0].sequenceEdges$ :
27379                 nd[0].spatialEdges$)
27380                 .filter(function (status) {
27381                 return status.cached;
27382             })
27383                 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
27384                 return [status, direction];
27385             });
27386         })
27387             .map(function (ed) {
27388             var direction = ed[1];
27389             for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
27390                 var edge = _a[_i];
27391                 if (edge.data.direction === direction) {
27392                     return edge.to;
27393                 }
27394             }
27395             return null;
27396         })
27397             .filter(function (key) {
27398             return key != null;
27399         })
27400             .switchMap(function (key) {
27401             return _this._navigator.graphService.cacheNode$(key);
27402         })
27403             .subscribe(function (node) {
27404             _this._navigator.stateService.appendNodes([node]);
27405         }, function (error) {
27406             console.error(error);
27407             _this.stop();
27408         });
27409         this._clearSubscription = this._navigator.stateService.currentNode$
27410             .bufferCount(1, 7)
27411             .subscribe(function (nodes) {
27412             _this._navigator.stateService.clearPriorNodes();
27413         });
27414         this.fire(SequenceComponent.playingchanged, true);
27415     };
27416     SequenceComponent.prototype._stop = function () {
27417         this._playingSubscription.unsubscribe();
27418         this._playingSubscription = null;
27419         this._clearSubscription.unsubscribe();
27420         this._clearSubscription = null;
27421         this.fire(SequenceComponent.playingchanged, false);
27422     };
27423     /** @inheritdoc */
27424     SequenceComponent.componentName = "sequence";
27425     /**
27426      * Event fired when playing starts or stops.
27427      *
27428      * @event PlayerComponent#playingchanged
27429      * @type {boolean} Indicates whether the player is playing.
27430      */
27431     SequenceComponent.playingchanged = "playingchanged";
27432     return SequenceComponent;
27433 }(Component_1.Component));
27434 exports.SequenceComponent = SequenceComponent;
27435 Component_1.ComponentService.register(SequenceComponent);
27436 exports.default = SequenceComponent;
27437
27438 },{"../../Component":230,"../../Edge":231,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/of":45,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/share":75,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/takeUntil":82,"rxjs/add/operator/withLatestFrom":85}],289:[function(require,module,exports){
27439 "use strict";
27440 Object.defineProperty(exports, "__esModule", { value: true });
27441 var Subject_1 = require("rxjs/Subject");
27442 var SequenceDOMInteraction = (function () {
27443     function SequenceDOMInteraction() {
27444         this._mouseEnterDirection$ = new Subject_1.Subject();
27445         this._mouseLeaveDirection$ = new Subject_1.Subject();
27446     }
27447     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
27448         get: function () {
27449             return this._mouseEnterDirection$;
27450         },
27451         enumerable: true,
27452         configurable: true
27453     });
27454     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
27455         get: function () {
27456             return this._mouseLeaveDirection$;
27457         },
27458         enumerable: true,
27459         configurable: true
27460     });
27461     return SequenceDOMInteraction;
27462 }());
27463 exports.SequenceDOMInteraction = SequenceDOMInteraction;
27464 exports.default = SequenceDOMInteraction;
27465
27466 },{"rxjs/Subject":34}],290:[function(require,module,exports){
27467 "use strict";
27468 /// <reference path="../../../typings/index.d.ts" />
27469 Object.defineProperty(exports, "__esModule", { value: true });
27470 var vd = require("virtual-dom");
27471 var Edge_1 = require("../../Edge");
27472 var SequenceDOMRenderer = (function () {
27473     function SequenceDOMRenderer(element) {
27474         this._minThresholdWidth = 320;
27475         this._maxThresholdWidth = 1480;
27476         this._minThresholdHeight = 240;
27477         this._maxThresholdHeight = 820;
27478     }
27479     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
27480         if (configuration.visible === false) {
27481             return vd.h("div.SequenceContainer", {}, []);
27482         }
27483         var nextKey = null;
27484         var prevKey = null;
27485         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27486             var edge = _a[_i];
27487             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
27488                 nextKey = edge.to;
27489             }
27490             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
27491                 prevKey = edge.to;
27492             }
27493         }
27494         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
27495         var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
27496         var containerProperties = {
27497             oncontextmenu: function (event) { event.preventDefault(); },
27498             style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
27499         };
27500         return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
27501     };
27502     SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
27503         var elementWidth = element.offsetWidth;
27504         var elementHeight = element.offsetHeight;
27505         var minWidth = configuration.minWidth;
27506         var maxWidth = configuration.maxWidth;
27507         if (maxWidth < minWidth) {
27508             maxWidth = minWidth;
27509         }
27510         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
27511         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
27512         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
27513         return minWidth + coeff * (maxWidth - minWidth);
27514     };
27515     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
27516         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
27517             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
27518         var onclick = configuration.playing ?
27519             function (e) { component.stop(); } :
27520             canPlay ? function (e) { component.play(); } : null;
27521         var buttonProperties = {
27522             onclick: onclick,
27523             style: {},
27524         };
27525         var iconClass = configuration.playing ?
27526             "Stop" :
27527             canPlay ? "Play" : "PlayDisabled";
27528         var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
27529         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
27530         return vd.h("div." + buttonClass, buttonProperties, [icon]);
27531     };
27532     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
27533         var nextProperties = {
27534             onclick: nextKey != null ?
27535                 function (e) {
27536                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
27537                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
27538                 } :
27539                 null,
27540             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
27541             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
27542             style: {},
27543         };
27544         var prevProperties = {
27545             onclick: prevKey != null ?
27546                 function (e) {
27547                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
27548                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
27549                 } :
27550                 null,
27551             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
27552             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
27553             style: {},
27554         };
27555         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
27556         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
27557         var nextIcon = vd.h("div.SequenceComponentIcon", []);
27558         var prevIcon = vd.h("div.SequenceComponentIcon", []);
27559         return [
27560             vd.h("div." + nextClass, nextProperties, [nextIcon]),
27561             vd.h("div." + prevClass, prevProperties, [prevIcon]),
27562         ];
27563     };
27564     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
27565         var className = direction === Edge_1.EdgeDirection.Next ?
27566             "SequenceStepNext" :
27567             "SequenceStepPrev";
27568         if (key == null) {
27569             className += "Disabled";
27570         }
27571         else {
27572             if (highlightKey === key) {
27573                 className += "Highlight";
27574             }
27575         }
27576         return className;
27577     };
27578     return SequenceDOMRenderer;
27579 }());
27580 exports.SequenceDOMRenderer = SequenceDOMRenderer;
27581 exports.default = SequenceDOMRenderer;
27582
27583 },{"../../Edge":231,"virtual-dom":186}],291:[function(require,module,exports){
27584 "use strict";
27585 Object.defineProperty(exports, "__esModule", { value: true });
27586 var GeometryTagError_1 = require("./error/GeometryTagError");
27587 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
27588 var PointGeometry_1 = require("./geometry/PointGeometry");
27589 exports.PointGeometry = PointGeometry_1.PointGeometry;
27590 var RectGeometry_1 = require("./geometry/RectGeometry");
27591 exports.RectGeometry = RectGeometry_1.RectGeometry;
27592 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
27593 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
27594 var OutlineTag_1 = require("./tag/OutlineTag");
27595 exports.OutlineTag = OutlineTag_1.OutlineTag;
27596 var SpotTag_1 = require("./tag/SpotTag");
27597 exports.SpotTag = SpotTag_1.SpotTag;
27598 var TagComponent_1 = require("./TagComponent");
27599 exports.TagComponent = TagComponent_1.TagComponent;
27600 var TagMode_1 = require("./TagMode");
27601 exports.TagMode = TagMode_1.TagMode;
27602
27603 },{"./TagComponent":292,"./TagMode":295,"./error/GeometryTagError":299,"./geometry/PointGeometry":301,"./geometry/PolygonGeometry":302,"./geometry/RectGeometry":303,"./tag/OutlineTag":315,"./tag/SpotTag":318}],292:[function(require,module,exports){
27604 "use strict";
27605 /// <reference path="../../../typings/index.d.ts" />
27606 var __extends = (this && this.__extends) || (function () {
27607     var extendStatics = Object.setPrototypeOf ||
27608         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27609         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27610     return function (d, b) {
27611         extendStatics(d, b);
27612         function __() { this.constructor = d; }
27613         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27614     };
27615 })();
27616 Object.defineProperty(exports, "__esModule", { value: true });
27617 var when = require("when");
27618 var Observable_1 = require("rxjs/Observable");
27619 require("rxjs/add/observable/combineLatest");
27620 require("rxjs/add/observable/empty");
27621 require("rxjs/add/observable/from");
27622 require("rxjs/add/observable/merge");
27623 require("rxjs/add/observable/of");
27624 require("rxjs/add/operator/combineLatest");
27625 require("rxjs/add/operator/concat");
27626 require("rxjs/add/operator/distinctUntilChanged");
27627 require("rxjs/add/operator/do");
27628 require("rxjs/add/operator/filter");
27629 require("rxjs/add/operator/map");
27630 require("rxjs/add/operator/merge");
27631 require("rxjs/add/operator/mergeMap");
27632 require("rxjs/add/operator/publishReplay");
27633 require("rxjs/add/operator/scan");
27634 require("rxjs/add/operator/share");
27635 require("rxjs/add/operator/skip");
27636 require("rxjs/add/operator/skipUntil");
27637 require("rxjs/add/operator/startWith");
27638 require("rxjs/add/operator/switchMap");
27639 require("rxjs/add/operator/take");
27640 require("rxjs/add/operator/takeUntil");
27641 require("rxjs/add/operator/withLatestFrom");
27642 var Component_1 = require("../../Component");
27643 var Geo_1 = require("../../Geo");
27644 var Render_1 = require("../../Render");
27645 /**
27646  * @class TagComponent
27647  *
27648  * @classdesc Component for showing and editing tags with different
27649  * geometries composed from 2D basic image coordinates (see the
27650  * {@link Viewer} class documentation for more information about coordinate
27651  * systems).
27652  *
27653  * The `add` method is used for adding new tags or replacing
27654  * tags already in the set. Tags are removed by id.
27655  *
27656  * If a tag already in the set has the same
27657  * id as one of the tags added, the old tag will be removed and
27658  * the added tag will take its place.
27659  *
27660  * The tag component mode can be set to either be non interactive or
27661  * to be in creating mode of a certain geometry type.
27662  *
27663  * The tag properties can be updated at any time and the change will
27664  * be visibile immediately.
27665  *
27666  * Tags are only relevant to a single image because they are based on
27667  * 2D basic image coordinates. Tags related to a certain image should
27668  * be removed when the viewer is moved to another node.
27669  *
27670  * To retrive and use the tag component
27671  *
27672  * @example
27673  * ```
27674  * var viewer = new Mapillary.Viewer(
27675  *     "<element-id>",
27676  *     "<client-id>",
27677  *     "<my key>",
27678  *     { component: { tag: true } });
27679  *
27680  * var tagComponent = viewer.getComponent("tag");
27681  * ```
27682  */
27683 var TagComponent = (function (_super) {
27684     __extends(TagComponent, _super);
27685     function TagComponent(name, container, navigator) {
27686         var _this = _super.call(this, name, container, navigator) || this;
27687         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
27688         _this._tagScene = new Component_1.TagScene();
27689         _this._tagSet = new Component_1.TagSet();
27690         _this._tagCreator = new Component_1.TagCreator(_this, navigator);
27691         _this._viewportCoords = new Geo_1.ViewportCoords();
27692         _this._createHandlers = {
27693             "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
27694             "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
27695             "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
27696             "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
27697             "Default": undefined,
27698         };
27699         _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
27700         _this._renderTags$ = _this._tagSet.changed$
27701             .map(function (tagSet) {
27702             var tags = tagSet.getAll();
27703             // ensure that tags are always rendered in the same order
27704             // to avoid hover tracking problems on first resize.
27705             tags.sort(function (t1, t2) {
27706                 var id1 = t1.tag.id;
27707                 var id2 = t2.tag.id;
27708                 if (id1 < id2) {
27709                     return -1;
27710                 }
27711                 if (id1 > id2) {
27712                     return 1;
27713                 }
27714                 return 0;
27715             });
27716             return tags;
27717         })
27718             .share();
27719         _this._tagChanged$ = _this._renderTags$
27720             .switchMap(function (tags) {
27721             return Observable_1.Observable
27722                 .from(tags)
27723                 .mergeMap(function (tag) {
27724                 return Observable_1.Observable
27725                     .merge(tag.tag.changed$, tag.tag.geometryChanged$);
27726             });
27727         })
27728             .share();
27729         _this._renderTagGLChanged$ = _this._renderTags$
27730             .switchMap(function (tags) {
27731             return Observable_1.Observable
27732                 .from(tags)
27733                 .mergeMap(function (tag) {
27734                 return tag.glObjectsChanged$;
27735             });
27736         })
27737             .share();
27738         _this._createGeometryChanged$ = _this._tagCreator.tag$
27739             .switchMap(function (tag) {
27740             return tag != null ?
27741                 tag.geometryChanged$ :
27742                 Observable_1.Observable.empty();
27743         })
27744             .share();
27745         _this._createGLObjectsChanged$ = _this._tagCreator.tag$
27746             .switchMap(function (tag) {
27747             return tag != null ?
27748                 tag.glObjectsChanged$ :
27749                 Observable_1.Observable.empty();
27750         })
27751             .share();
27752         _this._creatingConfiguration$ = _this._configuration$
27753             .distinctUntilChanged(function (c1, c2) {
27754             return c1.mode === c2.mode;
27755         }, function (configuration) {
27756             return {
27757                 createColor: configuration.createColor,
27758                 mode: configuration.mode,
27759             };
27760         })
27761             .publishReplay(1)
27762             .refCount();
27763         _this._creatingConfiguration$
27764             .subscribe(function (configuration) {
27765             _this.fire(TagComponent.modechanged, configuration.mode);
27766         });
27767         return _this;
27768     }
27769     /**
27770      * Add tags to the tag set or replace tags in the tag set.
27771      *
27772      * @description If a tag already in the set has the same
27773      * id as one of the tags added, the old tag will be removed
27774      * the added tag will take its place.
27775      *
27776      * @param {Array<Tag>} tags - Tags to add.
27777      *
27778      * @example ```tagComponent.add([tag1, tag2]);```
27779      */
27780     TagComponent.prototype.add = function (tags) {
27781         var _this = this;
27782         if (this._activated) {
27783             this._navigator.stateService.currentTransform$
27784                 .first()
27785                 .subscribe(function (transform) {
27786                 _this._tagSet.add(tags, transform);
27787                 var renderTags = tags
27788                     .map(function (tag) {
27789                     return _this._tagSet.get(tag.id);
27790                 });
27791                 _this._tagScene.add(renderTags);
27792             });
27793         }
27794         else {
27795             this._tagSet.addDeactivated(tags);
27796         }
27797     };
27798     /**
27799      * Change the current tag mode.
27800      *
27801      * @description Change the tag mode to one of the create modes for creating new geometries.
27802      *
27803      * @param {TagMode} mode - New tag mode.
27804      *
27805      * @fires TagComponent#modechanged
27806      *
27807      * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
27808      */
27809     TagComponent.prototype.changeMode = function (mode) {
27810         this.configure({ mode: mode });
27811     };
27812     /**
27813      * Returns the tag in the tag set with the specified id, or
27814      * undefined if the id matches no tag.
27815      *
27816      * @param {string} tagId - Id of the tag.
27817      *
27818      * @example ```var tag = tagComponent.get("tagId");```
27819      */
27820     TagComponent.prototype.get = function (tagId) {
27821         if (this._activated) {
27822             var renderTag = this._tagSet.get(tagId);
27823             return renderTag !== undefined ? renderTag.tag : undefined;
27824         }
27825         else {
27826             return this._tagSet.getDeactivated(tagId);
27827         }
27828     };
27829     /**
27830      * Returns an array of all tags.
27831      *
27832      * @example ```var tags = tagComponent.getAll();```
27833      */
27834     TagComponent.prototype.getAll = function () {
27835         if (this.activated) {
27836             return this._tagSet
27837                 .getAll()
27838                 .map(function (renderTag) {
27839                 return renderTag.tag;
27840             });
27841         }
27842         else {
27843             return this._tagSet.getAllDeactivated();
27844         }
27845     };
27846     /**
27847      * Returns an array of tag ids for tags that contain the specified point.
27848      *
27849      * @description The pixel point must lie inside the polygon or rectangle
27850      * of an added tag for the tag id to be returned. Tag ids for
27851      * tags that do not have a fill will also be returned if the point is inside
27852      * the geometry of the tag. Tags with point geometries can not be retrieved.
27853      *
27854      * No tag ids will be returned for panoramas.
27855      *
27856      * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
27857      *
27858      * With this function, you can use the coordinates provided by mouse
27859      * events to get information out of the tag component.
27860      *
27861      * If no tag at exist the pixel point, an empty array will be returned.
27862      *
27863      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
27864      * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
27865      *
27866      * @example
27867      * ```
27868      * tagComponent.getTagIdsAt([100, 100])
27869      *     .then((tagIds) => { console.log(tagIds); });
27870      * ```
27871      */
27872     TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
27873         var _this = this;
27874         return when.promise(function (resolve, reject) {
27875             _this._container.renderService.renderCamera$
27876                 .first()
27877                 .map(function (render) {
27878                 var viewport = _this._viewportCoords
27879                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
27880                 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
27881                 return ids;
27882             })
27883                 .subscribe(function (ids) {
27884                 resolve(ids);
27885             }, function (error) {
27886                 reject(error);
27887             });
27888         });
27889     };
27890     /**
27891      * Check if a tag exist in the tag set.
27892      *
27893      * @param {string} tagId - Id of the tag.
27894      *
27895      * @example ```var tagExists = tagComponent.has("tagId");```
27896      */
27897     TagComponent.prototype.has = function (tagId) {
27898         return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
27899     };
27900     /**
27901      * Remove tags with the specified ids from the tag set.
27902      *
27903      * @param {Array<string>} tagIds - Ids for tags to remove.
27904      *
27905      * @example ```tagComponent.remove(["id-1", "id-2"]);```
27906      */
27907     TagComponent.prototype.remove = function (tagIds) {
27908         if (this._activated) {
27909             this._tagSet.remove(tagIds);
27910             this._tagScene.remove(tagIds);
27911         }
27912         else {
27913             this._tagSet.removeDeactivated(tagIds);
27914         }
27915     };
27916     /**
27917      * Remove all tags from the tag set.
27918      *
27919      * @example ```tagComponent.removeAll();```
27920      */
27921     TagComponent.prototype.removeAll = function () {
27922         if (this._activated) {
27923             this._tagSet.removeAll();
27924             this._tagScene.removeAll();
27925         }
27926         else {
27927             this._tagSet.removeAllDeactivated();
27928         }
27929     };
27930     TagComponent.prototype._activate = function () {
27931         var _this = this;
27932         this._editVertexHandler.enable();
27933         var handlerGeometryCreated$ = Observable_1.Observable
27934             .from(Object.keys(this._createHandlers))
27935             .map(function (key) {
27936             return _this._createHandlers[key];
27937         })
27938             .filter(function (handler) {
27939             return !!handler;
27940         })
27941             .mergeMap(function (handler) {
27942             return handler.geometryCreated$;
27943         })
27944             .share();
27945         this._fireGeometryCreatedSubscription = handlerGeometryCreated$
27946             .subscribe(function (geometry) {
27947             _this.fire(TagComponent.geometrycreated, geometry);
27948         });
27949         this._fireCreateGeometryEventSubscription = this._tagCreator.tag$
27950             .skipWhile(function (tag) {
27951             return tag == null;
27952         })
27953             .distinctUntilChanged()
27954             .subscribe(function (tag) {
27955             var eventType = tag != null ?
27956                 TagComponent.creategeometrystart :
27957                 TagComponent.creategeometryend;
27958             _this.fire(eventType, _this);
27959         });
27960         this._handlerStopCreateSubscription = handlerGeometryCreated$
27961             .subscribe(function () {
27962             _this.changeMode(Component_1.TagMode.Default);
27963         });
27964         this._handlerEnablerSubscription = this._creatingConfiguration$
27965             .subscribe(function (configuration) {
27966             _this._disableCreateHandlers();
27967             var mode = Component_1.TagMode[configuration.mode];
27968             var handler = _this._createHandlers[mode];
27969             if (!!handler) {
27970                 handler.enable();
27971             }
27972         });
27973         this._fireTagsChangedSubscription = this._renderTags$
27974             .subscribe(function (tags) {
27975             _this.fire(TagComponent.tagschanged, _this);
27976         });
27977         this._stopCreateSubscription = this._tagCreator.tag$
27978             .switchMap(function (tag) {
27979             return tag != null ?
27980                 tag.aborted$
27981                     .map(function (t) { return null; }) :
27982                 Observable_1.Observable.empty();
27983         })
27984             .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
27985         this._setGLCreateTagSubscription = this._tagCreator.tag$
27986             .subscribe(function (tag) {
27987             if (_this._tagScene.hasCreateTag()) {
27988                 _this._tagScene.removeCreateTag();
27989             }
27990             if (tag != null) {
27991                 _this._tagScene.addCreateTag(tag);
27992             }
27993         });
27994         this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
27995             .subscribe(function (tag) {
27996             _this._tagScene.updateCreateTagObjects(tag);
27997         });
27998         this._updateGLObjectsSubscription = this._renderTagGLChanged$
27999             .subscribe(function (tag) {
28000             _this._tagScene.updateObjects(tag);
28001         });
28002         this._updateTagSceneSubscription = this._tagChanged$
28003             .subscribe(function (tag) {
28004             _this._tagScene.update();
28005         });
28006         this._domSubscription = this._renderTags$
28007             .startWith([])
28008             .do(function (tags) {
28009             _this._container.domRenderer.render$.next({
28010                 name: _this._name,
28011                 vnode: _this._tagDomRenderer.clear(),
28012             });
28013         })
28014             .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._container.renderService.size$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), function (renderTags, rc, atlas, size, tag, ct) {
28015             return [rc, atlas, size, renderTags, tag, ct];
28016         })
28017             .map(function (args) {
28018             return {
28019                 name: _this._name,
28020                 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
28021             };
28022         })
28023             .subscribe(this._container.domRenderer.render$);
28024         this._glSubscription = this._navigator.stateService.currentState$
28025             .map(function (frame) {
28026             var tagScene = _this._tagScene;
28027             return {
28028                 name: _this._name,
28029                 render: {
28030                     frameId: frame.id,
28031                     needsRender: tagScene.needsRender,
28032                     render: tagScene.render.bind(tagScene),
28033                     stage: Render_1.GLRenderStage.Foreground,
28034                 },
28035             };
28036         })
28037             .subscribe(this._container.glRenderer.render$);
28038         this._navigator.stateService.currentTransform$
28039             .first()
28040             .subscribe(function (transform) {
28041             _this._tagSet.activate(transform);
28042             _this._tagScene.add(_this._tagSet.getAll());
28043         });
28044     };
28045     TagComponent.prototype._deactivate = function () {
28046         this._editVertexHandler.disable();
28047         this._disableCreateHandlers();
28048         this._tagScene.clear();
28049         this._tagSet.deactivate();
28050         this._tagCreator.delete$.next(null);
28051         this._updateGLObjectsSubscription.unsubscribe();
28052         this._updateTagSceneSubscription.unsubscribe();
28053         this._stopCreateSubscription.unsubscribe();
28054         this._setGLCreateTagSubscription.unsubscribe();
28055         this._createGLObjectsChangedSubscription.unsubscribe();
28056         this._domSubscription.unsubscribe();
28057         this._glSubscription.unsubscribe();
28058         this._fireCreateGeometryEventSubscription.unsubscribe();
28059         this._fireGeometryCreatedSubscription.unsubscribe();
28060         this._fireTagsChangedSubscription.unsubscribe();
28061         this._handlerStopCreateSubscription.unsubscribe();
28062         this._handlerEnablerSubscription.unsubscribe();
28063         this._container.element.classList.remove("component-tag-create");
28064     };
28065     TagComponent.prototype._getDefaultConfiguration = function () {
28066         return {
28067             createColor: 0xFFFFFF,
28068             mode: Component_1.TagMode.Default,
28069         };
28070     };
28071     TagComponent.prototype._disableCreateHandlers = function () {
28072         var createHandlers = this._createHandlers;
28073         for (var key in createHandlers) {
28074             if (!createHandlers.hasOwnProperty(key)) {
28075                 continue;
28076             }
28077             var handler = createHandlers[key];
28078             if (!!handler) {
28079                 handler.disable();
28080             }
28081         }
28082     };
28083     /** @inheritdoc */
28084     TagComponent.componentName = "tag";
28085     /**
28086      * Event fired when an interaction to create a geometry ends.
28087      *
28088      * @description A create interaction can by a geometry being created
28089      * or by the creation being aborted.
28090      *
28091      * @event TagComponent#creategeometryend
28092      * @type {TagComponent} Tag component.
28093      * @example
28094      * ```
28095      * tagComponent.on("creategeometryend", function(component) {
28096      *     console.log(component);
28097      * });
28098      * ```
28099      */
28100     TagComponent.creategeometryend = "creategeometryend";
28101     /**
28102      * Event fired when an interaction to create a geometry starts.
28103      *
28104      * @description A create interaction starts when the first vertex
28105      * is created in the geometry.
28106      *
28107      * @event TagComponent#creategeometrystart
28108      * @type {TagComponent} Tag component.
28109      * @example
28110      * ```
28111      * tagComponent.on("creategeometrystart", function(component) {
28112      *     console.log(component);
28113      * });
28114      * ```
28115      */
28116     TagComponent.creategeometrystart = "creategeometrystart";
28117     /**
28118      * Event fired when the create mode is changed.
28119      *
28120      * @event TagComponent#modechanged
28121      * @type {TagMode} Tag mode
28122      * @example
28123      * ```
28124      * tagComponent.on("modechanged", function(mode) {
28125      *     console.log(mode);
28126      * });
28127      * ```
28128      */
28129     TagComponent.modechanged = "modechanged";
28130     /**
28131      * Event fired when a geometry has been created.
28132      *
28133      * @event TagComponent#geometrycreated
28134      * @type {Geometry} Created geometry.
28135      * @example
28136      * ```
28137      * tagComponent.on("geometrycreated", function(geometry) {
28138      *     console.log(geometry);
28139      * });
28140      * ```
28141      */
28142     TagComponent.geometrycreated = "geometrycreated";
28143     /**
28144      * Event fired when the tags collection has changed.
28145      *
28146      * @event TagComponent#tagschanged
28147      * @type {TagComponent} Tag component.
28148      * @example
28149      * ```
28150      * tagComponent.on("tagschanged", function(component) {
28151      *     console.log(component.getAll());
28152      * });
28153      * ```
28154      */
28155     TagComponent.tagschanged = "tagschanged";
28156     return TagComponent;
28157 }(Component_1.Component));
28158 exports.TagComponent = TagComponent;
28159 Component_1.ComponentService.register(TagComponent);
28160 exports.default = TagComponent;
28161
28162 },{"../../Component":230,"../../Geo":233,"../../Render":236,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/empty":40,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/share":75,"rxjs/add/operator/skip":76,"rxjs/add/operator/skipUntil":77,"rxjs/add/operator/startWith":79,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/take":81,"rxjs/add/operator/takeUntil":82,"rxjs/add/operator/withLatestFrom":85,"when":227}],293:[function(require,module,exports){
28163 "use strict";
28164 Object.defineProperty(exports, "__esModule", { value: true });
28165 var Subject_1 = require("rxjs/Subject");
28166 require("rxjs/add/operator/map");
28167 require("rxjs/add/operator/scan");
28168 require("rxjs/add/operator/share");
28169 require("rxjs/add/operator/withLatestFrom");
28170 var Component_1 = require("../../Component");
28171 var TagCreator = (function () {
28172     function TagCreator(component, navigator) {
28173         this._component = component;
28174         this._navigator = navigator;
28175         this._tagOperation$ = new Subject_1.Subject();
28176         this._createPolygon$ = new Subject_1.Subject();
28177         this._createRect$ = new Subject_1.Subject();
28178         this._delete$ = new Subject_1.Subject();
28179         this._tag$ = this._tagOperation$
28180             .scan(function (tag, operation) {
28181             return operation(tag);
28182         }, null)
28183             .share();
28184         this._createRect$
28185             .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
28186             .map(function (_a) {
28187             var coord = _a[0], conf = _a[1], transform = _a[2];
28188             return function (tag) {
28189                 var geometry = new Component_1.RectGeometry([
28190                     coord[0],
28191                     coord[1],
28192                     coord[0],
28193                     coord[1],
28194                 ]);
28195                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
28196             };
28197         })
28198             .subscribe(this._tagOperation$);
28199         this._createPolygon$
28200             .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
28201             .map(function (_a) {
28202             var coord = _a[0], conf = _a[1], transform = _a[2];
28203             return function (tag) {
28204                 var geometry = new Component_1.PolygonGeometry([
28205                     [coord[0], coord[1]],
28206                     [coord[0], coord[1]],
28207                     [coord[0], coord[1]],
28208                 ]);
28209                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
28210             };
28211         })
28212             .subscribe(this._tagOperation$);
28213         this._delete$
28214             .map(function () {
28215             return function (tag) {
28216                 return null;
28217             };
28218         })
28219             .subscribe(this._tagOperation$);
28220     }
28221     Object.defineProperty(TagCreator.prototype, "createRect$", {
28222         get: function () {
28223             return this._createRect$;
28224         },
28225         enumerable: true,
28226         configurable: true
28227     });
28228     Object.defineProperty(TagCreator.prototype, "createPolygon$", {
28229         get: function () {
28230             return this._createPolygon$;
28231         },
28232         enumerable: true,
28233         configurable: true
28234     });
28235     Object.defineProperty(TagCreator.prototype, "delete$", {
28236         get: function () {
28237             return this._delete$;
28238         },
28239         enumerable: true,
28240         configurable: true
28241     });
28242     Object.defineProperty(TagCreator.prototype, "tag$", {
28243         get: function () {
28244             return this._tag$;
28245         },
28246         enumerable: true,
28247         configurable: true
28248     });
28249     return TagCreator;
28250 }());
28251 exports.TagCreator = TagCreator;
28252 exports.default = TagCreator;
28253
28254 },{"../../Component":230,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":74,"rxjs/add/operator/share":75,"rxjs/add/operator/withLatestFrom":85}],294:[function(require,module,exports){
28255 "use strict";
28256 /// <reference path="../../../typings/index.d.ts" />
28257 Object.defineProperty(exports, "__esModule", { value: true });
28258 var vd = require("virtual-dom");
28259 var TagDOMRenderer = (function () {
28260     function TagDOMRenderer() {
28261     }
28262     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
28263         var vNodes = [];
28264         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28265             var tag = tags_1[_i];
28266             vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
28267         }
28268         if (createTag != null) {
28269             vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
28270         }
28271         return vd.h("div.TagContainer", {}, vNodes);
28272     };
28273     TagDOMRenderer.prototype.clear = function () {
28274         return vd.h("div", {}, []);
28275     };
28276     return TagDOMRenderer;
28277 }());
28278 exports.TagDOMRenderer = TagDOMRenderer;
28279
28280 },{"virtual-dom":186}],295:[function(require,module,exports){
28281 "use strict";
28282 Object.defineProperty(exports, "__esModule", { value: true });
28283 /**
28284  * Enumeration for tag modes
28285  * @enum {number}
28286  * @readonly
28287  * @description Modes for the interaction in the tag component.
28288  */
28289 var TagMode;
28290 (function (TagMode) {
28291     /**
28292      * Disables creating tags.
28293      */
28294     TagMode[TagMode["Default"] = 0] = "Default";
28295     /**
28296      * Create a point geometry through a click.
28297      */
28298     TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
28299     /**
28300      * Create a polygon geometry through clicks.
28301      */
28302     TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
28303     /**
28304      * Create a rect geometry through clicks.
28305      */
28306     TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
28307     /**
28308      * Create a rect geometry through drag.
28309      *
28310      * @description Claims the mouse which results in mouse handlers like
28311      * drag pan and scroll zoom becoming inactive.
28312      */
28313     TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
28314 })(TagMode = exports.TagMode || (exports.TagMode = {}));
28315 exports.default = TagMode;
28316
28317 },{}],296:[function(require,module,exports){
28318 "use strict";
28319 Object.defineProperty(exports, "__esModule", { value: true });
28320 var TagOperation;
28321 (function (TagOperation) {
28322     TagOperation[TagOperation["None"] = 0] = "None";
28323     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
28324     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
28325 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
28326 exports.default = TagOperation;
28327
28328 },{}],297:[function(require,module,exports){
28329 "use strict";
28330 /// <reference path="../../../typings/index.d.ts" />
28331 Object.defineProperty(exports, "__esModule", { value: true });
28332 var THREE = require("three");
28333 var TagScene = (function () {
28334     function TagScene(scene, raycaster) {
28335         this._createTag = null;
28336         this._needsRender = false;
28337         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
28338         this._scene = !!scene ? scene : new THREE.Scene();
28339         this._objectTags = {};
28340         this._retrievableObjects = [];
28341         this._tags = {};
28342     }
28343     Object.defineProperty(TagScene.prototype, "needsRender", {
28344         get: function () {
28345             return this._needsRender;
28346         },
28347         enumerable: true,
28348         configurable: true
28349     });
28350     TagScene.prototype.add = function (tags) {
28351         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28352             var tag = tags_1[_i];
28353             if (tag.tag.id in this._tags) {
28354                 this._remove(tag.tag.id);
28355             }
28356             this._add(tag);
28357         }
28358         this._needsRender = true;
28359     };
28360     TagScene.prototype.addCreateTag = function (tag) {
28361         for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
28362             var object = _a[_i];
28363             this._scene.add(object);
28364         }
28365         this._createTag = { tag: tag, objects: tag.glObjects };
28366         this._needsRender = true;
28367     };
28368     TagScene.prototype.clear = function () {
28369         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
28370             var id = _a[_i];
28371             this._remove(id);
28372         }
28373         this._needsRender = false;
28374     };
28375     TagScene.prototype.get = function (id) {
28376         return this.has(id) ? this._tags[id].tag : undefined;
28377     };
28378     TagScene.prototype.has = function (id) {
28379         return id in this._tags;
28380     };
28381     TagScene.prototype.hasCreateTag = function () {
28382         return this._createTag != null;
28383     };
28384     TagScene.prototype.intersectObjects = function (_a, camera) {
28385         var viewportX = _a[0], viewportY = _a[1];
28386         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
28387         var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
28388         var intersectedIds = [];
28389         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
28390             var intersect = intersects_1[_i];
28391             if (intersect.object.uuid in this._objectTags) {
28392                 intersectedIds.push(this._objectTags[intersect.object.uuid]);
28393             }
28394         }
28395         return intersectedIds;
28396     };
28397     TagScene.prototype.remove = function (ids) {
28398         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28399             var id = ids_1[_i];
28400             this._remove(id);
28401         }
28402         this._needsRender = true;
28403     };
28404     TagScene.prototype.removeAll = function () {
28405         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
28406             var id = _a[_i];
28407             this._remove(id);
28408         }
28409         this._needsRender = true;
28410     };
28411     TagScene.prototype.removeCreateTag = function () {
28412         if (this._createTag == null) {
28413             return;
28414         }
28415         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
28416             var object = _a[_i];
28417             this._scene.remove(object);
28418         }
28419         this._createTag.tag.dispose();
28420         this._createTag = null;
28421         this._needsRender = true;
28422     };
28423     TagScene.prototype.render = function (perspectiveCamera, renderer) {
28424         renderer.render(this._scene, perspectiveCamera);
28425         this._needsRender = false;
28426     };
28427     TagScene.prototype.update = function () {
28428         this._needsRender = true;
28429     };
28430     TagScene.prototype.updateCreateTagObjects = function (tag) {
28431         if (this._createTag.tag !== tag) {
28432             throw new Error("Create tags do not have the same reference.");
28433         }
28434         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
28435             var object = _a[_i];
28436             this._scene.remove(object);
28437         }
28438         for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
28439             var object = _c[_b];
28440             this._scene.add(object);
28441         }
28442         this._createTag.objects = tag.glObjects;
28443         this._needsRender = true;
28444     };
28445     TagScene.prototype.updateObjects = function (tag) {
28446         var id = tag.tag.id;
28447         if (this._tags[id].tag !== tag) {
28448             throw new Error("Tags do not have the same reference.");
28449         }
28450         var tagObjects = this._tags[id];
28451         this._removeObjects(tagObjects);
28452         delete this._tags[id];
28453         this._add(tag);
28454         this._needsRender = true;
28455     };
28456     TagScene.prototype._add = function (tag) {
28457         var id = tag.tag.id;
28458         var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
28459         this._tags[id] = tagObjects;
28460         for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
28461             var object = _a[_i];
28462             tagObjects.objects.push(object);
28463             this._scene.add(object);
28464         }
28465         for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
28466             var retrievableObject = _c[_b];
28467             tagObjects.retrievableObjects.push(retrievableObject);
28468             this._retrievableObjects.push(retrievableObject);
28469             this._objectTags[retrievableObject.uuid] = tag.tag.id;
28470         }
28471     };
28472     TagScene.prototype._remove = function (id) {
28473         var tagObjects = this._tags[id];
28474         this._removeObjects(tagObjects);
28475         tagObjects.tag.dispose();
28476         delete this._tags[id];
28477     };
28478     TagScene.prototype._removeObjects = function (tagObjects) {
28479         for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
28480             var object = _a[_i];
28481             this._scene.remove(object);
28482         }
28483         for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
28484             var retrievableObject = _c[_b];
28485             var index = this._retrievableObjects.indexOf(retrievableObject);
28486             if (index !== -1) {
28487                 this._retrievableObjects.splice(index, 1);
28488             }
28489         }
28490     };
28491     return TagScene;
28492 }());
28493 exports.TagScene = TagScene;
28494 exports.default = TagScene;
28495
28496 },{"three":180}],298:[function(require,module,exports){
28497 "use strict";
28498 Object.defineProperty(exports, "__esModule", { value: true });
28499 var Subject_1 = require("rxjs/Subject");
28500 require("rxjs/add/operator/map");
28501 require("rxjs/add/operator/scan");
28502 require("rxjs/add/operator/share");
28503 var Component_1 = require("../../Component");
28504 var TagSet = (function () {
28505     function TagSet() {
28506         this._active = false;
28507         this._hash = {};
28508         this._hashDeactivated = {};
28509         this._notifyChanged$ = new Subject_1.Subject();
28510     }
28511     Object.defineProperty(TagSet.prototype, "active", {
28512         get: function () {
28513             return this._active;
28514         },
28515         enumerable: true,
28516         configurable: true
28517     });
28518     Object.defineProperty(TagSet.prototype, "changed$", {
28519         get: function () {
28520             return this._notifyChanged$;
28521         },
28522         enumerable: true,
28523         configurable: true
28524     });
28525     TagSet.prototype.activate = function (transform) {
28526         if (this._active) {
28527             return;
28528         }
28529         for (var id in this._hashDeactivated) {
28530             if (!this._hashDeactivated.hasOwnProperty(id)) {
28531                 continue;
28532             }
28533             var tag = this._hashDeactivated[id];
28534             this._add(tag, transform);
28535         }
28536         this._hashDeactivated = {};
28537         this._active = true;
28538         this._notifyChanged$.next(this);
28539     };
28540     TagSet.prototype.deactivate = function () {
28541         if (!this._active) {
28542             return;
28543         }
28544         for (var id in this._hash) {
28545             if (!this._hash.hasOwnProperty(id)) {
28546                 continue;
28547             }
28548             this._hashDeactivated[id] = this._hash[id].tag;
28549         }
28550         this._hash = {};
28551         this._active = false;
28552     };
28553     TagSet.prototype.add = function (tags, transform) {
28554         this._assertActivationState(true);
28555         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28556             var tag = tags_1[_i];
28557             this._add(tag, transform);
28558         }
28559         this._notifyChanged$.next(this);
28560     };
28561     TagSet.prototype.addDeactivated = function (tags) {
28562         this._assertActivationState(false);
28563         for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
28564             var tag = tags_2[_i];
28565             if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
28566                 throw new Error("Tag type not supported");
28567             }
28568             this._hashDeactivated[tag.id] = tag;
28569         }
28570     };
28571     TagSet.prototype.get = function (id) {
28572         return this.has(id) ? this._hash[id] : undefined;
28573     };
28574     TagSet.prototype.getAll = function () {
28575         var hash = this._hash;
28576         return Object.keys(hash)
28577             .map(function (id) {
28578             return hash[id];
28579         });
28580     };
28581     TagSet.prototype.getAllDeactivated = function () {
28582         var hashDeactivated = this._hashDeactivated;
28583         return Object.keys(hashDeactivated)
28584             .map(function (id) {
28585             return hashDeactivated[id];
28586         });
28587     };
28588     TagSet.prototype.getDeactivated = function (id) {
28589         return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
28590     };
28591     TagSet.prototype.has = function (id) {
28592         return id in this._hash;
28593     };
28594     TagSet.prototype.hasDeactivated = function (id) {
28595         return id in this._hashDeactivated;
28596     };
28597     TagSet.prototype.remove = function (ids) {
28598         this._assertActivationState(true);
28599         var hash = this._hash;
28600         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28601             var id = ids_1[_i];
28602             if (!(id in hash)) {
28603                 continue;
28604             }
28605             delete hash[id];
28606         }
28607         this._notifyChanged$.next(this);
28608     };
28609     TagSet.prototype.removeAll = function () {
28610         this._assertActivationState(true);
28611         this._hash = {};
28612         this._notifyChanged$.next(this);
28613     };
28614     TagSet.prototype.removeAllDeactivated = function () {
28615         this._assertActivationState(false);
28616         this._hashDeactivated = {};
28617     };
28618     TagSet.prototype.removeDeactivated = function (ids) {
28619         this._assertActivationState(false);
28620         var hashDeactivated = this._hashDeactivated;
28621         for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
28622             var id = ids_2[_i];
28623             if (!(id in hashDeactivated)) {
28624                 continue;
28625             }
28626             delete hashDeactivated[id];
28627         }
28628     };
28629     TagSet.prototype._add = function (tag, transform) {
28630         if (tag instanceof Component_1.OutlineTag) {
28631             this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
28632         }
28633         else if (tag instanceof Component_1.SpotTag) {
28634             this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
28635         }
28636         else {
28637             throw new Error("Tag type not supported");
28638         }
28639     };
28640     TagSet.prototype._assertActivationState = function (should) {
28641         if (should !== this._active) {
28642             throw new Error("Tag set not in correct state for operation.");
28643         }
28644     };
28645     return TagSet;
28646 }());
28647 exports.TagSet = TagSet;
28648 exports.default = TagSet;
28649
28650 },{"../../Component":230,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":74,"rxjs/add/operator/share":75}],299:[function(require,module,exports){
28651 "use strict";
28652 var __extends = (this && this.__extends) || (function () {
28653     var extendStatics = Object.setPrototypeOf ||
28654         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28655         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28656     return function (d, b) {
28657         extendStatics(d, b);
28658         function __() { this.constructor = d; }
28659         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28660     };
28661 })();
28662 Object.defineProperty(exports, "__esModule", { value: true });
28663 var Error_1 = require("../../../Error");
28664 var GeometryTagError = (function (_super) {
28665     __extends(GeometryTagError, _super);
28666     function GeometryTagError(message) {
28667         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
28668         _this.name = "GeometryTagError";
28669         return _this;
28670     }
28671     return GeometryTagError;
28672 }(Error_1.MapillaryError));
28673 exports.GeometryTagError = GeometryTagError;
28674 exports.default = Error_1.MapillaryError;
28675
28676 },{"../../../Error":232}],300:[function(require,module,exports){
28677 "use strict";
28678 Object.defineProperty(exports, "__esModule", { value: true });
28679 var Subject_1 = require("rxjs/Subject");
28680 /**
28681  * @class Geometry
28682  * @abstract
28683  * @classdesc Represents a geometry.
28684  */
28685 var Geometry = (function () {
28686     /**
28687      * Create a geometry.
28688      *
28689      * @constructor
28690      */
28691     function Geometry() {
28692         this._notifyChanged$ = new Subject_1.Subject();
28693     }
28694     Object.defineProperty(Geometry.prototype, "changed$", {
28695         /**
28696          * Get changed observable.
28697          *
28698          * @description Emits the geometry itself every time the geometry
28699          * has changed.
28700          *
28701          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
28702          * @ignore
28703          */
28704         get: function () {
28705             return this._notifyChanged$;
28706         },
28707         enumerable: true,
28708         configurable: true
28709     });
28710     return Geometry;
28711 }());
28712 exports.Geometry = Geometry;
28713 exports.default = Geometry;
28714
28715 },{"rxjs/Subject":34}],301:[function(require,module,exports){
28716 "use strict";
28717 var __extends = (this && this.__extends) || (function () {
28718     var extendStatics = Object.setPrototypeOf ||
28719         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28720         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28721     return function (d, b) {
28722         extendStatics(d, b);
28723         function __() { this.constructor = d; }
28724         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28725     };
28726 })();
28727 Object.defineProperty(exports, "__esModule", { value: true });
28728 var Component_1 = require("../../../Component");
28729 /**
28730  * @class PointGeometry
28731  *
28732  * @classdesc Represents a point geometry in the 2D basic image coordinate system.
28733  *
28734  * @example
28735  * ```
28736  * var basicPoint = [0.5, 0.7];
28737  * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
28738  * ```
28739  */
28740 var PointGeometry = (function (_super) {
28741     __extends(PointGeometry, _super);
28742     /**
28743      * Create a point geometry.
28744      *
28745      * @constructor
28746      * @param {Array<number>} point - An array representing the basic coordinates of
28747      * the point.
28748      *
28749      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
28750      */
28751     function PointGeometry(point) {
28752         var _this = _super.call(this) || this;
28753         var x = point[0];
28754         var y = point[1];
28755         if (x < 0 || x > 1 || y < 0 || y > 1) {
28756             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28757         }
28758         _this._point = point.slice();
28759         return _this;
28760     }
28761     Object.defineProperty(PointGeometry.prototype, "point", {
28762         /**
28763          * Get point property.
28764          * @returns {Array<number>} Array representing the basic coordinates of the point.
28765          */
28766         get: function () {
28767             return this._point;
28768         },
28769         enumerable: true,
28770         configurable: true
28771     });
28772     /**
28773      * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
28774      * basic coordinates of the point itself.
28775      *
28776      * @returns {Array<number>} 2D basic coordinates representing the centroid.
28777      */
28778     PointGeometry.prototype.getCentroid2d = function () {
28779         return this._point.slice();
28780     };
28781     /**
28782      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
28783      * world coordinates of the point itself.
28784      *
28785      * @param {Transform} transform - The transform of the node related to the point.
28786      * @returns {Array<number>} 3D world coordinates representing the centroid.
28787      */
28788     PointGeometry.prototype.getCentroid3d = function (transform) {
28789         return transform.unprojectBasic(this._point, 200);
28790     };
28791     /**
28792      * Set the centroid of the point, i.e. the point coordinates.
28793      *
28794      * @param {Array<number>} value - The new value of the centroid.
28795      * @param {Transform} transform - The transform of the node related to the point.
28796      */
28797     PointGeometry.prototype.setCentroid2d = function (value, transform) {
28798         var changed = [
28799             Math.max(0, Math.min(1, value[0])),
28800             Math.max(0, Math.min(1, value[1])),
28801         ];
28802         this._point[0] = changed[0];
28803         this._point[1] = changed[1];
28804         this._notifyChanged$.next(this);
28805     };
28806     return PointGeometry;
28807 }(Component_1.Geometry));
28808 exports.PointGeometry = PointGeometry;
28809
28810 },{"../../../Component":230}],302:[function(require,module,exports){
28811 "use strict";
28812 var __extends = (this && this.__extends) || (function () {
28813     var extendStatics = Object.setPrototypeOf ||
28814         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28815         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28816     return function (d, b) {
28817         extendStatics(d, b);
28818         function __() { this.constructor = d; }
28819         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28820     };
28821 })();
28822 Object.defineProperty(exports, "__esModule", { value: true });
28823 var Component_1 = require("../../../Component");
28824 /**
28825  * @class PolygonGeometry
28826  *
28827  * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
28828  * All polygons and holes provided to the constructor needs to be closed.
28829  *
28830  * @example
28831  * ```
28832  * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
28833  * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
28834  * ```
28835  */
28836 var PolygonGeometry = (function (_super) {
28837     __extends(PolygonGeometry, _super);
28838     /**
28839      * Create a polygon geometry.
28840      *
28841      * @constructor
28842      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
28843      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
28844      * Each array of holes vertices must be closed.
28845      *
28846      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
28847      */
28848     function PolygonGeometry(polygon, holes) {
28849         var _this = _super.call(this) || this;
28850         var polygonLength = polygon.length;
28851         if (polygonLength < 3) {
28852             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
28853         }
28854         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
28855             polygon[0][1] !== polygon[polygonLength - 1][1]) {
28856             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
28857         }
28858         _this._polygon = [];
28859         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
28860             var vertex = polygon_1[_i];
28861             if (vertex[0] < 0 || vertex[0] > 1 ||
28862                 vertex[1] < 0 || vertex[1] > 1) {
28863                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
28864             }
28865             _this._polygon.push(vertex.slice());
28866         }
28867         _this._holes = [];
28868         if (holes == null) {
28869             return _this;
28870         }
28871         for (var i = 0; i < holes.length; i++) {
28872             var hole = holes[i];
28873             var holeLength = hole.length;
28874             if (holeLength < 3) {
28875                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
28876             }
28877             if (hole[0][0] !== hole[holeLength - 1][0] ||
28878                 hole[0][1] !== hole[holeLength - 1][1]) {
28879                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
28880             }
28881             _this._holes.push([]);
28882             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
28883                 var vertex = hole_1[_a];
28884                 if (vertex[0] < 0 || vertex[0] > 1 ||
28885                     vertex[1] < 0 || vertex[1] > 1) {
28886                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
28887                 }
28888                 _this._holes[i].push(vertex.slice());
28889             }
28890         }
28891         return _this;
28892     }
28893     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
28894         /**
28895          * Get polygon property.
28896          * @returns {Array<Array<number>>} Closed 2d polygon.
28897          */
28898         get: function () {
28899             return this._polygon;
28900         },
28901         enumerable: true,
28902         configurable: true
28903     });
28904     Object.defineProperty(PolygonGeometry.prototype, "holes", {
28905         /**
28906          * Get holes property.
28907          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
28908          */
28909         get: function () {
28910             return this._holes;
28911         },
28912         enumerable: true,
28913         configurable: true
28914     });
28915     /**
28916      * Add a vertex to the polygon by appending it after the last vertex.
28917      *
28918      * @param {Array<number>} vertex - Vertex to add.
28919      */
28920     PolygonGeometry.prototype.addVertex2d = function (vertex) {
28921         var clamped = [
28922             Math.max(0, Math.min(1, vertex[0])),
28923             Math.max(0, Math.min(1, vertex[1])),
28924         ];
28925         this._polygon.splice(this._polygon.length - 1, 0, clamped);
28926         this._notifyChanged$.next(this);
28927     };
28928     /**
28929      * Get the coordinates of a vertex from the polygon representation of the geometry.
28930      *
28931      * @description The first vertex represents the bottom-left corner with the rest of
28932      * the vertices following in clockwise order.
28933      *
28934      * @param {number} index - Vertex index.
28935      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
28936      */
28937     PolygonGeometry.prototype.getVertex2d = function (index) {
28938         return this._polygon[index].slice();
28939     };
28940     /**
28941      * Remove a vertex from the polygon.
28942      *
28943      * @param {number} index - The index of the vertex to remove.
28944      */
28945     PolygonGeometry.prototype.removeVertex2d = function (index) {
28946         if (index < 0 ||
28947             index >= this._polygon.length ||
28948             this._polygon.length < 4) {
28949             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
28950         }
28951         if (index > 0 && index < this._polygon.length - 1) {
28952             this._polygon.splice(index, 1);
28953         }
28954         else {
28955             this._polygon.splice(0, 1);
28956             this._polygon.pop();
28957             var closing = this._polygon[0].slice();
28958             this._polygon.push(closing);
28959         }
28960         this._notifyChanged$.next(this);
28961     };
28962     /** @inheritdoc */
28963     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
28964         var changed = [
28965             Math.max(0, Math.min(1, value[0])),
28966             Math.max(0, Math.min(1, value[1])),
28967         ];
28968         if (index === 0 || index === this._polygon.length - 1) {
28969             this._polygon[0] = changed.slice();
28970             this._polygon[this._polygon.length - 1] = changed.slice();
28971         }
28972         else {
28973             this._polygon[index] = changed.slice();
28974         }
28975         this._notifyChanged$.next(this);
28976     };
28977     /** @inheritdoc */
28978     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
28979         var xs = this._polygon.map(function (point) { return point[0]; });
28980         var ys = this._polygon.map(function (point) { return point[1]; });
28981         var minX = Math.min.apply(Math, xs);
28982         var maxX = Math.max.apply(Math, xs);
28983         var minY = Math.min.apply(Math, ys);
28984         var maxY = Math.max.apply(Math, ys);
28985         var centroid = this.getCentroid2d();
28986         var minTranslationX = -minX;
28987         var maxTranslationX = 1 - maxX;
28988         var minTranslationY = -minY;
28989         var maxTranslationY = 1 - maxY;
28990         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
28991         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
28992         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
28993             var point = _a[_i];
28994             point[0] += translationX;
28995             point[1] += translationY;
28996         }
28997         this._notifyChanged$.next(this);
28998     };
28999     /** @inheritdoc */
29000     PolygonGeometry.prototype.getPoints3d = function (transform) {
29001         return this.getVertices3d(transform);
29002     };
29003     /** @inheritdoc */
29004     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
29005         return transform.unprojectBasic(this._polygon[index], 200);
29006     };
29007     /** @inheritdoc */
29008     PolygonGeometry.prototype.getVertices2d = function () {
29009         return this._polygon.slice();
29010     };
29011     /** @inheritdoc */
29012     PolygonGeometry.prototype.getVertices3d = function (transform) {
29013         return this._polygon
29014             .map(function (point) {
29015             return transform.unprojectBasic(point, 200);
29016         });
29017     };
29018     /**
29019      * Get a polygon representation of the 3D coordinates for the vertices of each hole
29020      * of the geometry.
29021      *
29022      * @param {Transform} transform - The transform of the node related to the geometry.
29023      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
29024      * representing the vertices of each hole of the geometry.
29025      */
29026     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
29027         var holes3d = [];
29028         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29029             var hole = _a[_i];
29030             var hole3d = hole
29031                 .map(function (point) {
29032                 return transform.unprojectBasic(point, 200);
29033             });
29034             holes3d.push(hole3d);
29035         }
29036         return holes3d;
29037     };
29038     /** @inheritdoc */
29039     PolygonGeometry.prototype.getCentroid2d = function () {
29040         var polygon = this._polygon;
29041         var area = 0;
29042         var centroidX = 0;
29043         var centroidY = 0;
29044         for (var i = 0; i < polygon.length - 1; i++) {
29045             var xi = polygon[i][0];
29046             var yi = polygon[i][1];
29047             var xi1 = polygon[i + 1][0];
29048             var yi1 = polygon[i + 1][1];
29049             var a = xi * yi1 - xi1 * yi;
29050             area += a;
29051             centroidX += (xi + xi1) * a;
29052             centroidY += (yi + yi1) * a;
29053         }
29054         area /= 2;
29055         centroidX /= 6 * area;
29056         centroidY /= 6 * area;
29057         return [centroidX, centroidY];
29058     };
29059     /** @inheritdoc */
29060     PolygonGeometry.prototype.getCentroid3d = function (transform) {
29061         var centroid2d = this.getCentroid2d();
29062         return transform.unprojectBasic(centroid2d, 200);
29063     };
29064     /** @inheritdoc */
29065     PolygonGeometry.prototype.getTriangles3d = function (transform) {
29066         return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
29067     };
29068     /** @inheritdoc */
29069     PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
29070         return this._getPoleOfInaccessibility2d(this._polygon.slice());
29071     };
29072     /** @inheritdoc */
29073     PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
29074         var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
29075         return transform.unprojectBasic(pole2d, 200);
29076     };
29077     return PolygonGeometry;
29078 }(Component_1.VertexGeometry));
29079 exports.PolygonGeometry = PolygonGeometry;
29080 exports.default = PolygonGeometry;
29081
29082 },{"../../../Component":230}],303:[function(require,module,exports){
29083 "use strict";
29084 var __extends = (this && this.__extends) || (function () {
29085     var extendStatics = Object.setPrototypeOf ||
29086         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29087         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29088     return function (d, b) {
29089         extendStatics(d, b);
29090         function __() { this.constructor = d; }
29091         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29092     };
29093 })();
29094 Object.defineProperty(exports, "__esModule", { value: true });
29095 var Component_1 = require("../../../Component");
29096 /**
29097  * @class RectGeometry
29098  *
29099  * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
29100  *
29101  * @example
29102  * ```
29103  * var basicRect = [0.5, 0.3, 0.7, 0.4];
29104  * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
29105  * ```
29106  */
29107 var RectGeometry = (function (_super) {
29108     __extends(RectGeometry, _super);
29109     /**
29110      * Create a rectangle geometry.
29111      *
29112      * @constructor
29113      * @param {Array<number>} rect - An array representing the top-left and bottom-right
29114      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
29115      *
29116      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
29117      */
29118     function RectGeometry(rect) {
29119         var _this = _super.call(this) || this;
29120         if (rect[1] > rect[3]) {
29121             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
29122         }
29123         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
29124             var coord = rect_1[_i];
29125             if (coord < 0 || coord > 1) {
29126                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
29127             }
29128         }
29129         _this._anchorIndex = undefined;
29130         _this._rect = rect.slice(0, 4);
29131         _this._inverted = _this._rect[0] > _this._rect[2];
29132         return _this;
29133     }
29134     Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
29135         /**
29136          * Get anchor index property.
29137          *
29138          * @returns {number} Index representing the current anchor property if
29139          * achoring indexing has been initialized. If anchor indexing has not been
29140          * initialized or has been terminated undefined will be returned.
29141          */
29142         get: function () {
29143             return this._anchorIndex;
29144         },
29145         enumerable: true,
29146         configurable: true
29147     });
29148     Object.defineProperty(RectGeometry.prototype, "inverted", {
29149         /**
29150          * Get inverted property.
29151          *
29152          * @returns {boolean} Boolean determining whether the rect geometry is
29153          * inverted. For panoramas the rect geometrye may be inverted.
29154          */
29155         get: function () {
29156             return this._inverted;
29157         },
29158         enumerable: true,
29159         configurable: true
29160     });
29161     Object.defineProperty(RectGeometry.prototype, "rect", {
29162         /**
29163          * Get rect property.
29164          *
29165          * @returns {Array<number>} Array representing the top-left and bottom-right
29166          * corners of the rectangle in basic coordinates.
29167          */
29168         get: function () {
29169             return this._rect;
29170         },
29171         enumerable: true,
29172         configurable: true
29173     });
29174     /**
29175      * Initialize anchor indexing to enable setting opposite vertex.
29176      *
29177      * @param {number} [index] - The index of the vertex to use as anchor.
29178      *
29179      * @throws {Error} If anchor indexing has already been initialized.
29180      * @throws {Error} If index is not valid (0 to 3).
29181      */
29182     RectGeometry.prototype.initializeAnchorIndexing = function (index) {
29183         if (this._anchorIndex !== undefined) {
29184             throw new Error("Anchor indexing is already initialized.");
29185         }
29186         if (index < 0 || index > 3) {
29187             throw new Error("Invalid anchor index: " + index + ".");
29188         }
29189         this._anchorIndex = index === undefined ? 0 : index;
29190     };
29191     /**
29192      * Terminate anchor indexing to disable setting pposite vertex.
29193      */
29194     RectGeometry.prototype.terminateAnchorIndexing = function () {
29195         this._anchorIndex = undefined;
29196     };
29197     /**
29198      * Set the value of the vertex opposite to the anchor in the polygon
29199      * representation of the rectangle.
29200      *
29201      * @description Setting the opposite vertex may change the anchor index.
29202      *
29203      * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
29204      * @param {Transform} transform - The transform of the node related to the rectangle.
29205      *
29206      * @throws {Error} When anchor indexing has not been initialized.
29207      */
29208     RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
29209         if (this._anchorIndex === undefined) {
29210             throw new Error("Anchor indexing needs to be initialized.");
29211         }
29212         var changed = [
29213             Math.max(0, Math.min(1, opposite[0])),
29214             Math.max(0, Math.min(1, opposite[1])),
29215         ];
29216         var original = this._rect.slice();
29217         var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
29218             this._anchorIndex === 1 ? [original[0], original[1]] :
29219                 this._anchorIndex === 2 ? [original[2], original[1]] :
29220                     [original[2], original[3]];
29221         if (transform.fullPano) {
29222             var deltaX = this._anchorIndex < 2 ?
29223                 changed[0] - original[2] :
29224                 changed[0] - original[0];
29225             if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
29226                 // right side passes boundary rightward
29227                 this._inverted = true;
29228                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29229             }
29230             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
29231                 // left side passes right side and boundary rightward
29232                 this._inverted = true;
29233                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29234             }
29235             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
29236                 this._inverted = false;
29237                 if (anchor[0] > changed[0]) {
29238                     // left side passes boundary rightward
29239                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29240                 }
29241                 else {
29242                     // left side passes right side and boundary rightward
29243                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29244                 }
29245             }
29246             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
29247                 // left side passes boundary leftward
29248                 this._inverted = true;
29249                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29250             }
29251             else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
29252                 // right side passes left side and boundary leftward
29253                 this._inverted = true;
29254                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29255             }
29256             else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
29257                 this._inverted = false;
29258                 if (anchor[0] > changed[0]) {
29259                     // right side passes boundary leftward
29260                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29261                 }
29262                 else {
29263                     // right side passes left side and boundary leftward
29264                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29265                 }
29266             }
29267             else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
29268                 // inverted and right side passes left side completing a loop
29269                 this._inverted = false;
29270                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29271             }
29272             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
29273                 // inverted and left side passes right side completing a loop
29274                 this._inverted = false;
29275                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29276             }
29277             else if (this._inverted) {
29278                 // if still inverted only top and bottom can switch
29279                 if (this._anchorIndex < 2) {
29280                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
29281                 }
29282                 else {
29283                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
29284                 }
29285             }
29286             else {
29287                 // if still not inverted treat as non full pano
29288                 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
29289                     this._anchorIndex = 0;
29290                 }
29291                 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
29292                     this._anchorIndex = 1;
29293                 }
29294                 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
29295                     this._anchorIndex = 2;
29296                 }
29297                 else {
29298                     this._anchorIndex = 3;
29299                 }
29300             }
29301             var rect = [];
29302             if (this._anchorIndex === 0) {
29303                 rect[0] = anchor[0];
29304                 rect[1] = changed[1];
29305                 rect[2] = changed[0];
29306                 rect[3] = anchor[1];
29307             }
29308             else if (this._anchorIndex === 1) {
29309                 rect[0] = anchor[0];
29310                 rect[1] = anchor[1];
29311                 rect[2] = changed[0];
29312                 rect[3] = changed[1];
29313             }
29314             else if (this._anchorIndex === 2) {
29315                 rect[0] = changed[0];
29316                 rect[1] = anchor[1];
29317                 rect[2] = anchor[0];
29318                 rect[3] = changed[1];
29319             }
29320             else {
29321                 rect[0] = changed[0];
29322                 rect[1] = changed[1];
29323                 rect[2] = anchor[0];
29324                 rect[3] = anchor[1];
29325             }
29326             if (!this._inverted && rect[0] > rect[2] ||
29327                 this._inverted && rect[0] < rect[2]) {
29328                 rect[0] = original[0];
29329                 rect[2] = original[2];
29330             }
29331             if (rect[1] > rect[3]) {
29332                 rect[1] = original[1];
29333                 rect[3] = original[3];
29334             }
29335             this._rect[0] = rect[0];
29336             this._rect[1] = rect[1];
29337             this._rect[2] = rect[2];
29338             this._rect[3] = rect[3];
29339         }
29340         else {
29341             if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
29342                 this._anchorIndex = 0;
29343             }
29344             else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
29345                 this._anchorIndex = 1;
29346             }
29347             else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
29348                 this._anchorIndex = 2;
29349             }
29350             else {
29351                 this._anchorIndex = 3;
29352             }
29353             var rect = [];
29354             if (this._anchorIndex === 0) {
29355                 rect[0] = anchor[0];
29356                 rect[1] = changed[1];
29357                 rect[2] = changed[0];
29358                 rect[3] = anchor[1];
29359             }
29360             else if (this._anchorIndex === 1) {
29361                 rect[0] = anchor[0];
29362                 rect[1] = anchor[1];
29363                 rect[2] = changed[0];
29364                 rect[3] = changed[1];
29365             }
29366             else if (this._anchorIndex === 2) {
29367                 rect[0] = changed[0];
29368                 rect[1] = anchor[1];
29369                 rect[2] = anchor[0];
29370                 rect[3] = changed[1];
29371             }
29372             else {
29373                 rect[0] = changed[0];
29374                 rect[1] = changed[1];
29375                 rect[2] = anchor[0];
29376                 rect[3] = anchor[1];
29377             }
29378             if (rect[0] > rect[2]) {
29379                 rect[0] = original[0];
29380                 rect[2] = original[2];
29381             }
29382             if (rect[1] > rect[3]) {
29383                 rect[1] = original[1];
29384                 rect[3] = original[3];
29385             }
29386             this._rect[0] = rect[0];
29387             this._rect[1] = rect[1];
29388             this._rect[2] = rect[2];
29389             this._rect[3] = rect[3];
29390         }
29391         this._notifyChanged$.next(this);
29392     };
29393     /**
29394      * Set the value of a vertex in the polygon representation of the rectangle.
29395      *
29396      * @description The polygon is defined to have the first vertex at the
29397      * bottom-left corner with the rest of the vertices following in clockwise order.
29398      *
29399      * @param {number} index - The index of the vertex to be set.
29400      * @param {Array<number>} value - The new value of the vertex.
29401      * @param {Transform} transform - The transform of the node related to the rectangle.
29402      */
29403     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
29404         var original = this._rect.slice();
29405         var changed = [
29406             Math.max(0, Math.min(1, value[0])),
29407             Math.max(0, Math.min(1, value[1])),
29408         ];
29409         var rect = [];
29410         if (index === 0) {
29411             rect[0] = changed[0];
29412             rect[1] = original[1];
29413             rect[2] = original[2];
29414             rect[3] = changed[1];
29415         }
29416         else if (index === 1) {
29417             rect[0] = changed[0];
29418             rect[1] = changed[1];
29419             rect[2] = original[2];
29420             rect[3] = original[3];
29421         }
29422         else if (index === 2) {
29423             rect[0] = original[0];
29424             rect[1] = changed[1];
29425             rect[2] = changed[0];
29426             rect[3] = original[3];
29427         }
29428         else if (index === 3) {
29429             rect[0] = original[0];
29430             rect[1] = original[1];
29431             rect[2] = changed[0];
29432             rect[3] = changed[1];
29433         }
29434         if (transform.fullPano) {
29435             var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
29436                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
29437             var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
29438                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
29439             if (passingBoundaryLeftward || passingBoundaryRightward) {
29440                 this._inverted = !this._inverted;
29441             }
29442             else {
29443                 if (rect[0] - original[0] < -0.25) {
29444                     rect[0] = original[0];
29445                 }
29446                 if (rect[2] - original[2] > 0.25) {
29447                     rect[2] = original[2];
29448                 }
29449             }
29450             if (!this._inverted && rect[0] > rect[2] ||
29451                 this._inverted && rect[0] < rect[2]) {
29452                 rect[0] = original[0];
29453                 rect[2] = original[2];
29454             }
29455         }
29456         else {
29457             if (rect[0] > rect[2]) {
29458                 rect[0] = original[0];
29459                 rect[2] = original[2];
29460             }
29461         }
29462         if (rect[1] > rect[3]) {
29463             rect[1] = original[1];
29464             rect[3] = original[3];
29465         }
29466         this._rect[0] = rect[0];
29467         this._rect[1] = rect[1];
29468         this._rect[2] = rect[2];
29469         this._rect[3] = rect[3];
29470         this._notifyChanged$.next(this);
29471     };
29472     /** @inheritdoc */
29473     RectGeometry.prototype.setCentroid2d = function (value, transform) {
29474         var original = this._rect.slice();
29475         var x0 = original[0];
29476         var x1 = this._inverted ? original[2] + 1 : original[2];
29477         var y0 = original[1];
29478         var y1 = original[3];
29479         var centerX = x0 + (x1 - x0) / 2;
29480         var centerY = y0 + (y1 - y0) / 2;
29481         var translationX = 0;
29482         if (transform.gpano != null &&
29483             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
29484             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
29485         }
29486         else {
29487             var minTranslationX = -x0;
29488             var maxTranslationX = 1 - x1;
29489             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
29490         }
29491         var minTranslationY = -y0;
29492         var maxTranslationY = 1 - y1;
29493         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
29494         this._rect[0] = original[0] + translationX;
29495         this._rect[1] = original[1] + translationY;
29496         this._rect[2] = original[2] + translationX;
29497         this._rect[3] = original[3] + translationY;
29498         if (this._rect[0] < 0) {
29499             this._rect[0] += 1;
29500             this._inverted = !this._inverted;
29501         }
29502         else if (this._rect[0] > 1) {
29503             this._rect[0] -= 1;
29504             this._inverted = !this._inverted;
29505         }
29506         if (this._rect[2] < 0) {
29507             this._rect[2] += 1;
29508             this._inverted = !this._inverted;
29509         }
29510         else if (this._rect[2] > 1) {
29511             this._rect[2] -= 1;
29512             this._inverted = !this._inverted;
29513         }
29514         this._notifyChanged$.next(this);
29515     };
29516     /**
29517      * Get the 3D coordinates for the vertices of the rectangle with
29518      * interpolated points along the lines.
29519      *
29520      * @param {Transform} transform - The transform of the node related to
29521      * the rectangle.
29522      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
29523      * representing the rectangle.
29524      */
29525     RectGeometry.prototype.getPoints3d = function (transform) {
29526         return this._getPoints2d(transform)
29527             .map(function (point) {
29528             return transform.unprojectBasic(point, 200);
29529         });
29530     };
29531     /**
29532      * Get the coordinates of a vertex from the polygon representation of the geometry.
29533      *
29534      * @description The first vertex represents the bottom-left corner with the rest of
29535      * the vertices following in clockwise order. The method shifts the right side
29536      * coordinates of the rectangle by one unit to ensure that the vertices are ordered
29537      * clockwise.
29538      *
29539      * @param {number} index - Vertex index.
29540      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
29541      */
29542     RectGeometry.prototype.getVertex2d = function (index) {
29543         return this._rectToVertices2d(this._rect)[index];
29544     };
29545     /**
29546      * Get the coordinates of a vertex from the polygon representation of the geometry.
29547      *
29548      * @description The first vertex represents the bottom-left corner with the rest of
29549      * the vertices following in clockwise order. The coordinates will not be shifted
29550      * so they may not appear in clockwise order when layed out on the plane.
29551      *
29552      * @param {number} index - Vertex index.
29553      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
29554      */
29555     RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
29556         return this._rectToNonAdjustedVertices2d(this._rect)[index];
29557     };
29558     /**
29559      * Get a vertex from the polygon representation of the 3D coordinates for the
29560      * vertices of the geometry.
29561      *
29562      * @description The first vertex represents the bottom-left corner with the rest of
29563      * the vertices following in clockwise order.
29564      *
29565      * @param {number} index - Vertex index.
29566      * @param {Transform} transform - The transform of the node related to the geometry.
29567      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
29568      * the vertices of the geometry.
29569      */
29570     RectGeometry.prototype.getVertex3d = function (index, transform) {
29571         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
29572     };
29573     /**
29574      * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
29575      *
29576      * @description The first vertex represents the bottom-left corner with the rest of
29577      * the vertices following in clockwise order.
29578      *
29579      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
29580      * the rectangle vertices.
29581      */
29582     RectGeometry.prototype.getVertices2d = function () {
29583         return this._rectToVertices2d(this._rect);
29584     };
29585     /**
29586      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
29587      *
29588      * @description The first vertex represents the bottom-left corner with the rest of
29589      * the vertices following in clockwise order.
29590      *
29591      * @param {Transform} transform - The transform of the node related to the rectangle.
29592      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
29593      * the rectangle vertices.
29594      */
29595     RectGeometry.prototype.getVertices3d = function (transform) {
29596         return this._rectToVertices2d(this._rect)
29597             .map(function (vertex) {
29598             return transform.unprojectBasic(vertex, 200);
29599         });
29600     };
29601     /** @inheritdoc */
29602     RectGeometry.prototype.getCentroid2d = function () {
29603         var rect = this._rect;
29604         var x0 = rect[0];
29605         var x1 = this._inverted ? rect[2] + 1 : rect[2];
29606         var y0 = rect[1];
29607         var y1 = rect[3];
29608         var centroidX = x0 + (x1 - x0) / 2;
29609         var centroidY = y0 + (y1 - y0) / 2;
29610         return [centroidX, centroidY];
29611     };
29612     /** @inheritdoc */
29613     RectGeometry.prototype.getCentroid3d = function (transform) {
29614         var centroid2d = this.getCentroid2d();
29615         return transform.unprojectBasic(centroid2d, 200);
29616     };
29617     /** @inheritdoc */
29618     RectGeometry.prototype.getPoleOfAccessibility2d = function () {
29619         return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
29620     };
29621     /** @inheritdoc */
29622     RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
29623         var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
29624         return transform.unprojectBasic(pole2d, 200);
29625     };
29626     /** @inheritdoc */
29627     RectGeometry.prototype.getTriangles3d = function (transform) {
29628         return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
29629     };
29630     /**
29631      * Check if a particular bottom-right value is valid according to the current
29632      * rectangle coordinates.
29633      *
29634      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
29635      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
29636      * are valid.
29637      */
29638     RectGeometry.prototype.validate = function (bottomRight) {
29639         var rect = this._rect;
29640         if (!this._inverted && bottomRight[0] < rect[0] ||
29641             bottomRight[0] - rect[2] > 0.25 ||
29642             bottomRight[1] < rect[1]) {
29643             return false;
29644         }
29645         return true;
29646     };
29647     /**
29648      * Get the 2D coordinates for the vertices of the rectangle with
29649      * interpolated points along the lines.
29650      *
29651      * @param {Transform} transform - The transform of the node related to
29652      * the rectangle.
29653      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
29654      * representing the rectangle.
29655      */
29656     RectGeometry.prototype._getPoints2d = function (transform) {
29657         var vertices2d = this._rectToVertices2d(this._rect);
29658         var sides = vertices2d.length - 1;
29659         var sections = 10;
29660         var points2d = [];
29661         for (var i = 0; i < sides; ++i) {
29662             var startX = vertices2d[i][0];
29663             var startY = vertices2d[i][1];
29664             var endX = vertices2d[i + 1][0];
29665             var endY = vertices2d[i + 1][1];
29666             var intervalX = (endX - startX) / (sections - 1);
29667             var intervalY = (endY - startY) / (sections - 1);
29668             for (var j = 0; j < sections; ++j) {
29669                 var point = [
29670                     startX + j * intervalX,
29671                     startY + j * intervalY,
29672                 ];
29673                 points2d.push(point);
29674             }
29675         }
29676         return points2d;
29677     };
29678     /**
29679      * Convert the top-left, bottom-right representation of a rectangle to a polygon
29680      * representation of the vertices starting at the bottom-left corner going
29681      * clockwise.
29682      *
29683      * @description The method shifts the right side coordinates of the rectangle
29684      * by one unit to ensure that the vertices are ordered clockwise.
29685      *
29686      * @param {Array<number>} rect - Top-left, bottom-right representation of a
29687      * rectangle.
29688      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
29689      * rectangle.
29690      */
29691     RectGeometry.prototype._rectToVertices2d = function (rect) {
29692         return [
29693             [rect[0], rect[3]],
29694             [rect[0], rect[1]],
29695             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
29696             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
29697             [rect[0], rect[3]],
29698         ];
29699     };
29700     /**
29701      * Convert the top-left, bottom-right representation of a rectangle to a polygon
29702      * representation of the vertices starting at the bottom-left corner going
29703      * clockwise.
29704      *
29705      * @description The first vertex represents the bottom-left corner with the rest of
29706      * the vertices following in clockwise order. The coordinates will not be shifted
29707      * to ensure that the vertices are ordered clockwise when layed out on the plane.
29708      *
29709      * @param {Array<number>} rect - Top-left, bottom-right representation of a
29710      * rectangle.
29711      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
29712      * rectangle.
29713      */
29714     RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
29715         return [
29716             [rect[0], rect[3]],
29717             [rect[0], rect[1]],
29718             [rect[2], rect[1]],
29719             [rect[2], rect[3]],
29720             [rect[0], rect[3]],
29721         ];
29722     };
29723     return RectGeometry;
29724 }(Component_1.VertexGeometry));
29725 exports.RectGeometry = RectGeometry;
29726 exports.default = RectGeometry;
29727
29728 },{"../../../Component":230}],304:[function(require,module,exports){
29729 "use strict";
29730 /// <reference path="../../../../typings/index.d.ts" />
29731 var __extends = (this && this.__extends) || (function () {
29732     var extendStatics = Object.setPrototypeOf ||
29733         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29734         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29735     return function (d, b) {
29736         extendStatics(d, b);
29737         function __() { this.constructor = d; }
29738         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29739     };
29740 })();
29741 Object.defineProperty(exports, "__esModule", { value: true });
29742 var earcut = require("earcut");
29743 var polylabel = require("@mapbox/polylabel");
29744 var Component_1 = require("../../../Component");
29745 /**
29746  * @class VertexGeometry
29747  * @abstract
29748  * @classdesc Represents a vertex geometry.
29749  */
29750 var VertexGeometry = (function (_super) {
29751     __extends(VertexGeometry, _super);
29752     /**
29753      * Create a vertex geometry.
29754      *
29755      * @constructor
29756      */
29757     function VertexGeometry() {
29758         return _super.call(this) || this;
29759     }
29760     /**
29761      * Finds the polygon pole of inaccessibility, the most distant internal
29762      * point from the polygon outline.
29763      *
29764      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
29765      * @returns {Array<number>} Point of inaccessibility.
29766      * @ignore
29767      */
29768     VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
29769         var pole2d = polylabel([points2d], 3e-2);
29770         return pole2d;
29771     };
29772     /**
29773      * Triangulates a 2d polygon and returns the triangle
29774      * representation as a flattened array of 3d points.
29775      *
29776      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
29777      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
29778      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
29779      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
29780      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
29781      * @ignore
29782      */
29783     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
29784         var data = [points2d.slice(0, -1)];
29785         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
29786             var hole2d = _a[_i];
29787             data.push(hole2d.slice(0, -1));
29788         }
29789         var points = points3d.slice(0, -1);
29790         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
29791             var hole3d = _c[_b];
29792             points = points.concat(hole3d.slice(0, -1));
29793         }
29794         var flattened = earcut.flatten(data);
29795         var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
29796         var triangles = [];
29797         for (var i = 0; i < indices.length; ++i) {
29798             var point = points[indices[i]];
29799             triangles.push(point[0]);
29800             triangles.push(point[1]);
29801             triangles.push(point[2]);
29802         }
29803         return triangles;
29804     };
29805     return VertexGeometry;
29806 }(Component_1.Geometry));
29807 exports.VertexGeometry = VertexGeometry;
29808 exports.default = VertexGeometry;
29809
29810 },{"../../../Component":230,"@mapbox/polylabel":1,"earcut":8}],305:[function(require,module,exports){
29811 "use strict";
29812 /// <reference path="../../../../typings/index.d.ts" />
29813 var __extends = (this && this.__extends) || (function () {
29814     var extendStatics = Object.setPrototypeOf ||
29815         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29816         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29817     return function (d, b) {
29818         extendStatics(d, b);
29819         function __() { this.constructor = d; }
29820         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29821     };
29822 })();
29823 Object.defineProperty(exports, "__esModule", { value: true });
29824 var Subject_1 = require("rxjs/Subject");
29825 var Component_1 = require("../../../Component");
29826 var CreateHandlerBase = (function (_super) {
29827     __extends(CreateHandlerBase, _super);
29828     function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
29829         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
29830         _this._tagCreator = tagCreator;
29831         _this._geometryCreated$ = new Subject_1.Subject();
29832         return _this;
29833     }
29834     Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
29835         get: function () {
29836             return this._geometryCreated$;
29837         },
29838         enumerable: true,
29839         configurable: true
29840     });
29841     CreateHandlerBase.prototype._enable = function () {
29842         this._enableCreate();
29843         this._container.element.classList.add("component-tag-create");
29844     };
29845     CreateHandlerBase.prototype._disable = function () {
29846         this._container.element.classList.remove("component-tag-create");
29847         this._disableCreate();
29848     };
29849     CreateHandlerBase.prototype._validateBasic = function (basic) {
29850         var x = basic[0];
29851         var y = basic[1];
29852         return 0 <= x && x <= 1 && 0 <= y && y <= 1;
29853     };
29854     CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
29855         var _this = this;
29856         return mouseEvent$
29857             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
29858             .map(function (_a) {
29859             var event = _a[0], camera = _a[1], transform = _a[2];
29860             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
29861         });
29862     };
29863     return CreateHandlerBase;
29864 }(Component_1.TagHandlerBase));
29865 exports.CreateHandlerBase = CreateHandlerBase;
29866 exports.default = CreateHandlerBase;
29867
29868 },{"../../../Component":230,"rxjs/Subject":34}],306:[function(require,module,exports){
29869 "use strict";
29870 var __extends = (this && this.__extends) || (function () {
29871     var extendStatics = Object.setPrototypeOf ||
29872         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29873         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29874     return function (d, b) {
29875         extendStatics(d, b);
29876         function __() { this.constructor = d; }
29877         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29878     };
29879 })();
29880 Object.defineProperty(exports, "__esModule", { value: true });
29881 var Component_1 = require("../../../Component");
29882 var CreatePointHandler = (function (_super) {
29883     __extends(CreatePointHandler, _super);
29884     function CreatePointHandler() {
29885         return _super !== null && _super.apply(this, arguments) || this;
29886     }
29887     CreatePointHandler.prototype._enableCreate = function () {
29888         this._container.mouseService.deferPixels(this._name, 4);
29889         this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$)
29890             .filter(this._validateBasic)
29891             .map(function (basic) {
29892             return new Component_1.PointGeometry(basic);
29893         })
29894             .subscribe(this._geometryCreated$);
29895     };
29896     CreatePointHandler.prototype._disableCreate = function () {
29897         this._container.mouseService.undeferPixels(this._name);
29898         this._geometryCreatedSubscription.unsubscribe();
29899     };
29900     CreatePointHandler.prototype._getNameExtension = function () {
29901         return "create-point";
29902     };
29903     return CreatePointHandler;
29904 }(Component_1.CreateHandlerBase));
29905 exports.CreatePointHandler = CreatePointHandler;
29906 exports.default = CreatePointHandler;
29907
29908 },{"../../../Component":230}],307:[function(require,module,exports){
29909 "use strict";
29910 var __extends = (this && this.__extends) || (function () {
29911     var extendStatics = Object.setPrototypeOf ||
29912         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29913         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29914     return function (d, b) {
29915         extendStatics(d, b);
29916         function __() { this.constructor = d; }
29917         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29918     };
29919 })();
29920 Object.defineProperty(exports, "__esModule", { value: true });
29921 var Component_1 = require("../../../Component");
29922 var CreatePolygonHandler = (function (_super) {
29923     __extends(CreatePolygonHandler, _super);
29924     function CreatePolygonHandler() {
29925         return _super !== null && _super.apply(this, arguments) || this;
29926     }
29927     CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
29928         tag.addPoint(basicPoint);
29929     };
29930     Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
29931         get: function () {
29932             return this._tagCreator.createPolygon$;
29933         },
29934         enumerable: true,
29935         configurable: true
29936     });
29937     CreatePolygonHandler.prototype._getNameExtension = function () {
29938         return "create-polygon";
29939     };
29940     CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
29941         tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
29942     };
29943     return CreatePolygonHandler;
29944 }(Component_1.CreateVertexHandler));
29945 exports.CreatePolygonHandler = CreatePolygonHandler;
29946 exports.default = CreatePolygonHandler;
29947
29948 },{"../../../Component":230}],308:[function(require,module,exports){
29949 "use strict";
29950 var __extends = (this && this.__extends) || (function () {
29951     var extendStatics = Object.setPrototypeOf ||
29952         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29953         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29954     return function (d, b) {
29955         extendStatics(d, b);
29956         function __() { this.constructor = d; }
29957         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29958     };
29959 })();
29960 Object.defineProperty(exports, "__esModule", { value: true });
29961 var Observable_1 = require("rxjs/Observable");
29962 var Component_1 = require("../../../Component");
29963 var CreateRectDragHandler = (function (_super) {
29964     __extends(CreateRectDragHandler, _super);
29965     function CreateRectDragHandler() {
29966         return _super !== null && _super.apply(this, arguments) || this;
29967     }
29968     CreateRectDragHandler.prototype._enableCreate = function () {
29969         var _this = this;
29970         this._container.mouseService.claimMouse(this._name, 2);
29971         this._deleteSubscription = this._navigator.stateService.currentTransform$
29972             .map(function (transform) { return null; })
29973             .skip(1)
29974             .subscribe(this._tagCreator.delete$);
29975         this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$))
29976             .filter(this._validateBasic)
29977             .subscribe(this._tagCreator.createRect$);
29978         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
29979             .filter(function (tag) {
29980             return !!tag;
29981         })
29982             .subscribe(function (tag) {
29983             tag.geometry.initializeAnchorIndexing();
29984         });
29985         var basicMouse$ = Observable_1.Observable
29986             .merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$))
29987             .combineLatest(this._container.renderService.renderCamera$)
29988             .withLatestFrom(this._navigator.stateService.currentTransform$)
29989             .map(function (_a) {
29990             var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
29991             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
29992         });
29993         this._setVertexSubscription = this._tagCreator.tag$
29994             .switchMap(function (tag) {
29995             return !!tag ?
29996                 Observable_1.Observable
29997                     .combineLatest(Observable_1.Observable.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
29998                 Observable_1.Observable.empty();
29999         })
30000             .subscribe(function (_a) {
30001             var tag = _a[0], basicPoint = _a[1], transform = _a[2];
30002             tag.geometry.setOppositeVertex2d(basicPoint, transform);
30003         });
30004         var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$
30005             .withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$))
30006             .filter(this._validateBasic), function (event, basicPoint) {
30007             return basicPoint;
30008         })
30009             .share();
30010         this._addPointSubscription = this._tagCreator.tag$
30011             .switchMap(function (tag) {
30012             return !!tag ?
30013                 Observable_1.Observable
30014                     .combineLatest(Observable_1.Observable.of(tag), basicMouseDragEnd$) :
30015                 Observable_1.Observable.empty();
30016         })
30017             .subscribe(function (_a) {
30018             var tag = _a[0], basicPoint = _a[1];
30019             var rectGeometry = tag.geometry;
30020             if (!rectGeometry.validate(basicPoint)) {
30021                 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
30022             }
30023             tag.addPoint(basicPoint);
30024         });
30025         this._geometryCreatedSubscription = this._tagCreator.tag$
30026             .switchMap(function (tag) {
30027             return !!tag ?
30028                 tag.created$
30029                     .map(function (t) {
30030                     return t.geometry;
30031                 }) :
30032                 Observable_1.Observable.empty();
30033         })
30034             .subscribe(this._geometryCreated$);
30035     };
30036     CreateRectDragHandler.prototype._disableCreate = function () {
30037         this._container.mouseService.unclaimMouse(this._name);
30038         this._tagCreator.delete$.next(null);
30039         this._addPointSubscription.unsubscribe();
30040         this._createSubscription.unsubscribe();
30041         this._deleteSubscription.unsubscribe();
30042         this._geometryCreatedSubscription.unsubscribe();
30043         this._initializeAnchorIndexingSubscription.unsubscribe();
30044         this._setVertexSubscription.unsubscribe();
30045     };
30046     CreateRectDragHandler.prototype._getNameExtension = function () {
30047         return "create-rect-drag";
30048     };
30049     return CreateRectDragHandler;
30050 }(Component_1.CreateHandlerBase));
30051 exports.CreateRectDragHandler = CreateRectDragHandler;
30052 exports.default = CreateRectDragHandler;
30053
30054 },{"../../../Component":230,"rxjs/Observable":29}],309:[function(require,module,exports){
30055 "use strict";
30056 var __extends = (this && this.__extends) || (function () {
30057     var extendStatics = Object.setPrototypeOf ||
30058         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30059         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30060     return function (d, b) {
30061         extendStatics(d, b);
30062         function __() { this.constructor = d; }
30063         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30064     };
30065 })();
30066 Object.defineProperty(exports, "__esModule", { value: true });
30067 var Component_1 = require("../../../Component");
30068 var CreateRectHandler = (function (_super) {
30069     __extends(CreateRectHandler, _super);
30070     function CreateRectHandler() {
30071         return _super !== null && _super.apply(this, arguments) || this;
30072     }
30073     Object.defineProperty(CreateRectHandler.prototype, "_create$", {
30074         get: function () {
30075             return this._tagCreator.createRect$;
30076         },
30077         enumerable: true,
30078         configurable: true
30079     });
30080     CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
30081         var rectGeometry = tag.geometry;
30082         if (!rectGeometry.validate(basicPoint)) {
30083             basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
30084         }
30085         tag.addPoint(basicPoint);
30086     };
30087     CreateRectHandler.prototype._enable = function () {
30088         _super.prototype._enable.call(this);
30089         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
30090             .filter(function (tag) {
30091             return !!tag;
30092         })
30093             .subscribe(function (tag) {
30094             tag.geometry.initializeAnchorIndexing();
30095         });
30096     };
30097     CreateRectHandler.prototype._disable = function () {
30098         _super.prototype._disable.call(this);
30099         this._initializeAnchorIndexingSubscription.unsubscribe();
30100     };
30101     CreateRectHandler.prototype._getNameExtension = function () {
30102         return "create-rect";
30103     };
30104     CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
30105         tag.geometry.setOppositeVertex2d(basicPoint, transform);
30106     };
30107     return CreateRectHandler;
30108 }(Component_1.CreateVertexHandler));
30109 exports.CreateRectHandler = CreateRectHandler;
30110 exports.default = CreateRectHandler;
30111
30112 },{"../../../Component":230}],310:[function(require,module,exports){
30113 "use strict";
30114 var __extends = (this && this.__extends) || (function () {
30115     var extendStatics = Object.setPrototypeOf ||
30116         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30117         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30118     return function (d, b) {
30119         extendStatics(d, b);
30120         function __() { this.constructor = d; }
30121         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30122     };
30123 })();
30124 Object.defineProperty(exports, "__esModule", { value: true });
30125 var Observable_1 = require("rxjs/Observable");
30126 var Component_1 = require("../../../Component");
30127 var CreateVertexHandler = (function (_super) {
30128     __extends(CreateVertexHandler, _super);
30129     function CreateVertexHandler() {
30130         return _super !== null && _super.apply(this, arguments) || this;
30131     }
30132     CreateVertexHandler.prototype._enableCreate = function () {
30133         var _this = this;
30134         this._container.mouseService.deferPixels(this._name, 4);
30135         var transformChanged$ = this._navigator.stateService.currentTransform$
30136             .map(function (transform) { })
30137             .publishReplay(1)
30138             .refCount();
30139         this._deleteSubscription = transformChanged$
30140             .skip(1)
30141             .subscribe(this._tagCreator.delete$);
30142         var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).share();
30143         this._createSubscription = transformChanged$
30144             .switchMap(function () {
30145             return basicClick$
30146                 .filter(_this._validateBasic)
30147                 .take(1);
30148         })
30149             .subscribe(this._create$);
30150         this._setVertexSubscription = this._tagCreator.tag$
30151             .switchMap(function (tag) {
30152             return !!tag ?
30153                 Observable_1.Observable
30154                     .combineLatest(Observable_1.Observable.of(tag), Observable_1.Observable
30155                     .merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
30156                 Observable_1.Observable.empty();
30157         })
30158             .subscribe(function (_a) {
30159             var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
30160             var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
30161             _this._setVertex2d(tag, basicPoint, transform);
30162         });
30163         this._addPointSubscription = this._tagCreator.tag$
30164             .switchMap(function (tag) {
30165             return !!tag ?
30166                 Observable_1.Observable
30167                     .combineLatest(Observable_1.Observable.of(tag), basicClick$) :
30168                 Observable_1.Observable.empty();
30169         })
30170             .subscribe(function (_a) {
30171             var tag = _a[0], basicPoint = _a[1];
30172             _this._addPoint(tag, basicPoint);
30173         });
30174         this._geometryCreateSubscription = this._tagCreator.tag$
30175             .switchMap(function (tag) {
30176             return !!tag ?
30177                 tag.created$
30178                     .map(function (t) {
30179                     return t.geometry;
30180                 }) :
30181                 Observable_1.Observable.empty();
30182         })
30183             .subscribe(this._geometryCreated$);
30184     };
30185     CreateVertexHandler.prototype._disableCreate = function () {
30186         this._container.mouseService.undeferPixels(this._name);
30187         this._tagCreator.delete$.next(null);
30188         this._addPointSubscription.unsubscribe();
30189         this._createSubscription.unsubscribe();
30190         this._deleteSubscription.unsubscribe();
30191         this._geometryCreateSubscription.unsubscribe();
30192         this._setVertexSubscription.unsubscribe();
30193     };
30194     return CreateVertexHandler;
30195 }(Component_1.CreateHandlerBase));
30196 exports.CreateVertexHandler = CreateVertexHandler;
30197 exports.default = CreateVertexHandler;
30198
30199 },{"../../../Component":230,"rxjs/Observable":29}],311:[function(require,module,exports){
30200 "use strict";
30201 var __extends = (this && this.__extends) || (function () {
30202     var extendStatics = Object.setPrototypeOf ||
30203         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30204         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30205     return function (d, b) {
30206         extendStatics(d, b);
30207         function __() { this.constructor = d; }
30208         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30209     };
30210 })();
30211 Object.defineProperty(exports, "__esModule", { value: true });
30212 var Observable_1 = require("rxjs/Observable");
30213 var Component_1 = require("../../../Component");
30214 var EditVertexHandler = (function (_super) {
30215     __extends(EditVertexHandler, _super);
30216     function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
30217         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
30218         _this._tagSet = tagSet;
30219         return _this;
30220     }
30221     EditVertexHandler.prototype._enable = function () {
30222         var _this = this;
30223         var interaction$ = this._tagSet.changed$
30224             .map(function (tagSet) {
30225             return tagSet.getAll();
30226         })
30227             .switchMap(function (tags) {
30228             return Observable_1.Observable
30229                 .from(tags)
30230                 .mergeMap(function (tag) {
30231                 return tag.interact$;
30232             });
30233         })
30234             .switchMap(function (interaction) {
30235             return Observable_1.Observable
30236                 .of(interaction)
30237                 .concat(_this._container.mouseService.documentMouseUp$
30238                 .map(function () {
30239                 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
30240             })
30241                 .first());
30242         })
30243             .share();
30244         var mouseMove$ = Observable_1.Observable
30245             .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
30246             .share();
30247         this._claimMouseSubscription = interaction$
30248             .switchMap(function (interaction) {
30249             return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : Observable_1.Observable.empty();
30250         })
30251             .subscribe(function () {
30252             _this._container.mouseService.claimMouse(_this._name, 3);
30253         });
30254         this._cursorSubscription = interaction$
30255             .map(function (interaction) {
30256             return interaction.cursor;
30257         })
30258             .distinctUntilChanged()
30259             .subscribe(function (cursor) {
30260             var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
30261             for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
30262                 var interactionCursor = interactionCursors_1[_i];
30263                 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
30264             }
30265             if (!!cursor) {
30266                 _this._container.element.classList.add("component-tag-edit-" + cursor);
30267             }
30268         });
30269         this._unclaimMouseSubscription = this._container.mouseService
30270             .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
30271             .subscribe(function (e) {
30272             _this._container.mouseService.unclaimMouse(_this._name);
30273         });
30274         this._preventDefaultSubscription = interaction$
30275             .switchMap(function (interaction) {
30276             return !!interaction.tag ?
30277                 _this._container.mouseService.documentMouseMove$ :
30278                 Observable_1.Observable.empty();
30279         })
30280             .subscribe(function (event) {
30281             event.preventDefault(); // prevent selection of content outside the viewer
30282         });
30283         this._updateGeometrySubscription = interaction$
30284             .withLatestFrom(mouseMove$)
30285             .switchMap(function (_a) {
30286             var interaction = _a[0], mouseMove = _a[1];
30287             if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
30288                 return Observable_1.Observable.empty();
30289             }
30290             var mouseDrag$ = Observable_1.Observable
30291                 .of(mouseMove)
30292                 .concat(_this._container.mouseService
30293                 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
30294                 .filter(function (event) {
30295                 return _this._viewportCoords.insideElement(event, _this._container.element);
30296             }));
30297             return Observable_1.Observable
30298                 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
30299                 .withLatestFrom(Observable_1.Observable.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
30300                 var event = _a[0], render = _a[1];
30301                 return [event, render, i, transform];
30302             });
30303         })
30304             .subscribe(function (_a) {
30305             var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
30306             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
30307             var geometry = interaction.tag.geometry;
30308             if (interaction.operation === Component_1.TagOperation.Centroid) {
30309                 geometry.setCentroid2d(basic, transform);
30310             }
30311             else if (interaction.operation === Component_1.TagOperation.Vertex) {
30312                 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
30313             }
30314         });
30315     };
30316     EditVertexHandler.prototype._disable = function () {
30317         this._claimMouseSubscription.unsubscribe();
30318         this._cursorSubscription.unsubscribe();
30319         this._preventDefaultSubscription.unsubscribe();
30320         this._unclaimMouseSubscription.unsubscribe();
30321         this._updateGeometrySubscription.unsubscribe();
30322     };
30323     EditVertexHandler.prototype._getNameExtension = function () {
30324         return "edit-vertex";
30325     };
30326     return EditVertexHandler;
30327 }(Component_1.TagHandlerBase));
30328 exports.EditVertexHandler = EditVertexHandler;
30329 exports.default = EditVertexHandler;
30330
30331 },{"../../../Component":230,"rxjs/Observable":29}],312:[function(require,module,exports){
30332 "use strict";
30333 /// <reference path="../../../../typings/index.d.ts" />
30334 var __extends = (this && this.__extends) || (function () {
30335     var extendStatics = Object.setPrototypeOf ||
30336         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30337         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30338     return function (d, b) {
30339         extendStatics(d, b);
30340         function __() { this.constructor = d; }
30341         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30342     };
30343 })();
30344 Object.defineProperty(exports, "__esModule", { value: true });
30345 var Component_1 = require("../../../Component");
30346 var TagHandlerBase = (function (_super) {
30347     __extends(TagHandlerBase, _super);
30348     function TagHandlerBase(component, container, navigator, viewportCoords) {
30349         var _this = _super.call(this, component, container, navigator) || this;
30350         _this._name = _this._component.name + "-" + _this._getNameExtension();
30351         _this._viewportCoords = viewportCoords;
30352         return _this;
30353     }
30354     TagHandlerBase.prototype._getConfiguration = function (enable) {
30355         return {};
30356     };
30357     TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
30358         offsetX = offsetX != null ? offsetX : 0;
30359         offsetY = offsetY != null ? offsetY : 0;
30360         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
30361         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
30362         return basic;
30363     };
30364     return TagHandlerBase;
30365 }(Component_1.HandlerBase));
30366 exports.TagHandlerBase = TagHandlerBase;
30367 exports.default = TagHandlerBase;
30368
30369 },{"../../../Component":230}],313:[function(require,module,exports){
30370 "use strict";
30371 /// <reference path="../../../../typings/index.d.ts" />
30372 Object.defineProperty(exports, "__esModule", { value: true });
30373 var THREE = require("three");
30374 var vd = require("virtual-dom");
30375 var Subject_1 = require("rxjs/Subject");
30376 var Component_1 = require("../../../Component");
30377 var Geo_1 = require("../../../Geo");
30378 var OutlineCreateTag = (function () {
30379     function OutlineCreateTag(geometry, options, transform, viewportCoords) {
30380         var _this = this;
30381         this._geometry = geometry;
30382         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
30383         this._transform = transform;
30384         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
30385         this._outline = this._createOutine();
30386         this._glObjects = [this._outline];
30387         this._aborted$ = new Subject_1.Subject();
30388         this._created$ = new Subject_1.Subject();
30389         this._glObjectsChanged$ = new Subject_1.Subject();
30390         this._geometryChangedSubscription = this._geometry.changed$
30391             .subscribe(function (vertexGeometry) {
30392             _this._disposeOutline();
30393             _this._outline = _this._createOutine();
30394             _this._glObjects = [_this._outline];
30395             _this._glObjectsChanged$.next(_this);
30396         });
30397     }
30398     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
30399         get: function () {
30400             return this._geometry;
30401         },
30402         enumerable: true,
30403         configurable: true
30404     });
30405     Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
30406         get: function () {
30407             return this._glObjects;
30408         },
30409         enumerable: true,
30410         configurable: true
30411     });
30412     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
30413         get: function () {
30414             return this._aborted$;
30415         },
30416         enumerable: true,
30417         configurable: true
30418     });
30419     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
30420         get: function () {
30421             return this._created$;
30422         },
30423         enumerable: true,
30424         configurable: true
30425     });
30426     Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
30427         get: function () {
30428             return this._glObjectsChanged$;
30429         },
30430         enumerable: true,
30431         configurable: true
30432     });
30433     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
30434         get: function () {
30435             var _this = this;
30436             return this._geometry.changed$
30437                 .map(function (geometry) {
30438                 return _this;
30439             });
30440         },
30441         enumerable: true,
30442         configurable: true
30443     });
30444     OutlineCreateTag.prototype.dispose = function () {
30445         this._disposeOutline();
30446         this._geometryChangedSubscription.unsubscribe();
30447     };
30448     OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
30449         var _this = this;
30450         var vNodes = [];
30451         var container = {
30452             offsetHeight: size.height, offsetWidth: size.width,
30453         };
30454         var abort = function (e) {
30455             e.stopPropagation();
30456             _this._aborted$.next(_this);
30457         };
30458         if (this._geometry instanceof Component_1.RectGeometry) {
30459             var anchorIndex = this._geometry.anchorIndex;
30460             var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
30461             var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
30462             var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
30463             if (canvasPoint != null) {
30464                 var background = this._colorToBackground(this._options.color);
30465                 var transform = this._canvasToTransform(canvasPoint);
30466                 var pointProperties = {
30467                     style: { background: background, transform: transform },
30468                 };
30469                 var completerProperties = {
30470                     onclick: abort,
30471                     style: { transform: transform },
30472                 };
30473                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
30474                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
30475             }
30476         }
30477         else if (this._geometry instanceof Component_1.PolygonGeometry) {
30478             var polygonGeometry_1 = this._geometry;
30479             var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
30480             var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
30481             if (firstVertexCanvas != null) {
30482                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
30483                     function (e) {
30484                         e.stopPropagation();
30485                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
30486                         _this._created$.next(_this);
30487                     } :
30488                     abort;
30489                 var transform = this._canvasToTransform(firstVertexCanvas);
30490                 var completerProperties = {
30491                     onclick: firstOnclick,
30492                     style: { transform: transform },
30493                 };
30494                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
30495                     "TagCompleter" :
30496                     "TagInteractor";
30497                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
30498             }
30499             if (polygonGeometry_1.polygon.length > 3) {
30500                 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
30501                 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
30502                 if (lastVertexCanvas != null) {
30503                     var remove = function (e) {
30504                         e.stopPropagation();
30505                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
30506                     };
30507                     var transform = this._canvasToTransform(lastVertexCanvas);
30508                     var completerProperties = {
30509                         onclick: remove,
30510                         style: { transform: transform },
30511                     };
30512                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
30513                 }
30514             }
30515             var verticesBasic = polygonGeometry_1.polygon.slice();
30516             verticesBasic.splice(-2, 2);
30517             for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
30518                 var vertexBasic = verticesBasic_1[_i];
30519                 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
30520                 if (vertexCanvas != null) {
30521                     var background = this._colorToBackground(this._options.color);
30522                     var transform = this._canvasToTransform(vertexCanvas);
30523                     var pointProperties = {
30524                         style: {
30525                             background: background,
30526                             transform: transform,
30527                         },
30528                     };
30529                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
30530                 }
30531             }
30532         }
30533         return vNodes;
30534     };
30535     OutlineCreateTag.prototype.addPoint = function (point) {
30536         if (this._geometry instanceof Component_1.RectGeometry) {
30537             var rectGeometry = this._geometry;
30538             if (!rectGeometry.validate(point)) {
30539                 return;
30540             }
30541             this._created$.next(this);
30542         }
30543         else if (this._geometry instanceof Component_1.PolygonGeometry) {
30544             var polygonGeometry = this._geometry;
30545             polygonGeometry.addVertex2d(point);
30546         }
30547     };
30548     OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
30549         var canvasX = Math.round(canvas[0]);
30550         var canvasY = Math.round(canvas[1]);
30551         var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
30552         return transform;
30553     };
30554     OutlineCreateTag.prototype._colorToBackground = function (color) {
30555         return "#" + ("000000" + color.toString(16)).substr(-6);
30556     };
30557     OutlineCreateTag.prototype._createOutine = function () {
30558         var polygon3d = this._geometry.getPoints3d(this._transform);
30559         var positions = this._getLinePositions(polygon3d);
30560         var geometry = new THREE.BufferGeometry();
30561         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
30562         var material = new THREE.LineBasicMaterial({
30563             color: this._options.color,
30564             linewidth: 1,
30565         });
30566         return new THREE.Line(geometry, material);
30567     };
30568     OutlineCreateTag.prototype._disposeOutline = function () {
30569         if (this._outline == null) {
30570             return;
30571         }
30572         var line = this._outline;
30573         line.geometry.dispose();
30574         line.material.dispose();
30575         this._outline = null;
30576         this._glObjects = [];
30577     };
30578     OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
30579         var length = polygon3d.length;
30580         var positions = new Float32Array(length * 3);
30581         for (var i = 0; i < length; ++i) {
30582             var index = 3 * i;
30583             var position = polygon3d[i];
30584             positions[index] = position[0];
30585             positions[index + 1] = position[1];
30586             positions[index + 2] = position[2];
30587         }
30588         return positions;
30589     };
30590     return OutlineCreateTag;
30591 }());
30592 exports.OutlineCreateTag = OutlineCreateTag;
30593 exports.default = OutlineCreateTag;
30594
30595 },{"../../../Component":230,"../../../Geo":233,"rxjs/Subject":34,"three":180,"virtual-dom":186}],314:[function(require,module,exports){
30596 "use strict";
30597 /// <reference path="../../../../typings/index.d.ts" />
30598 var __extends = (this && this.__extends) || (function () {
30599     var extendStatics = Object.setPrototypeOf ||
30600         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30601         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30602     return function (d, b) {
30603         extendStatics(d, b);
30604         function __() { this.constructor = d; }
30605         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30606     };
30607 })();
30608 Object.defineProperty(exports, "__esModule", { value: true });
30609 var THREE = require("three");
30610 var vd = require("virtual-dom");
30611 var Component_1 = require("../../../Component");
30612 /**
30613  * @class OutlineRenderTag
30614  * @classdesc Tag visualizing the properties of an OutlineTag.
30615  */
30616 var OutlineRenderTag = (function (_super) {
30617     __extends(OutlineRenderTag, _super);
30618     function OutlineRenderTag(tag, transform) {
30619         var _this = _super.call(this, tag, transform) || this;
30620         _this._fill = !transform.gpano ?
30621             _this._createFill() :
30622             null;
30623         _this._holes = _this._tag.lineWidth >= 1 ?
30624             _this._createHoles() :
30625             [];
30626         _this._outline = _this._tag.lineWidth >= 1 ?
30627             _this._createOutline() :
30628             null;
30629         _this._geometryChangedSubscription = _this._tag.geometry.changed$
30630             .subscribe(function (geometry) {
30631             if (_this._fill != null) {
30632                 _this._updateFillGeometry();
30633             }
30634             if (_this._holes.length > 0) {
30635                 _this._updateHoleGeometries();
30636             }
30637             if (_this._outline != null) {
30638                 _this._updateOulineGeometry();
30639             }
30640         });
30641         _this._changedSubscription = _this._tag.changed$
30642             .subscribe(function (changedTag) {
30643             var glObjectsChanged = false;
30644             if (_this._fill != null) {
30645                 _this._updateFillMaterial(_this._fill.material);
30646             }
30647             if (_this._outline == null) {
30648                 if (_this._tag.lineWidth >= 1) {
30649                     _this._holes = _this._createHoles();
30650                     _this._outline = _this._createOutline();
30651                     glObjectsChanged = true;
30652                 }
30653             }
30654             else {
30655                 _this._updateHoleMaterials();
30656                 _this._updateOutlineMaterial();
30657             }
30658             if (glObjectsChanged) {
30659                 _this._glObjectsChanged$.next(_this);
30660             }
30661         });
30662         return _this;
30663     }
30664     OutlineRenderTag.prototype.dispose = function () {
30665         this._disposeFill();
30666         this._disposeHoles();
30667         this._disposeOutline();
30668         this._changedSubscription.unsubscribe();
30669         this._geometryChangedSubscription.unsubscribe();
30670     };
30671     OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
30672         var _this = this;
30673         var vNodes = [];
30674         var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
30675         var isPerspective = !this._transform.gpano;
30676         var container = {
30677             offsetHeight: size.height, offsetWidth: size.width,
30678         };
30679         if (this._tag.icon != null && (isRect || isPerspective)) {
30680             var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
30681                 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
30682                 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
30683             var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
30684             if (iconCanvas != null) {
30685                 var interact = function (e) {
30686                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
30687                 };
30688                 if (atlas.loaded) {
30689                     var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
30690                     var iconCanvasX = Math.round(iconCanvas[0]);
30691                     var iconCanvasY = Math.round(iconCanvas[1]);
30692                     var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
30693                     var click = function (e) {
30694                         e.stopPropagation();
30695                         _this._tag.click$.next(_this._tag);
30696                     };
30697                     var properties = {
30698                         onclick: click,
30699                         onmousedown: interact,
30700                         style: { transform: transform },
30701                     };
30702                     vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
30703                 }
30704             }
30705         }
30706         else if (this._tag.text != null && (isRect || isPerspective)) {
30707             var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
30708                 this._tag.geometry.getVertex2d(3) :
30709                 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
30710             var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
30711             if (textCanvas != null) {
30712                 var textCanvasX = Math.round(textCanvas[0]);
30713                 var textCanvasY = Math.round(textCanvas[1]);
30714                 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
30715                     "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
30716                     "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
30717                 var interact = function (e) {
30718                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
30719                 };
30720                 var properties = {
30721                     onmousedown: interact,
30722                     style: {
30723                         color: this._colorToCss(this._tag.textColor),
30724                         transform: transform,
30725                     },
30726                     textContent: this._tag.text,
30727                 };
30728                 vNodes.push(vd.h("span.TagSymbol", properties, []));
30729             }
30730         }
30731         if (!this._tag.editable) {
30732             return vNodes;
30733         }
30734         var lineColor = this._colorToCss(this._tag.lineColor);
30735         if (this._tag.geometry instanceof Component_1.RectGeometry) {
30736             var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
30737             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
30738             if (centroidCanvas != null) {
30739                 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
30740                 var centroidCanvasX = Math.round(centroidCanvas[0]);
30741                 var centroidCanvasY = Math.round(centroidCanvas[1]);
30742                 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
30743                 var properties = {
30744                     onmousedown: interact,
30745                     style: { background: lineColor, transform: transform },
30746                 };
30747                 vNodes.push(vd.h("div.TagMover", properties, []));
30748             }
30749         }
30750         var vertices2d = this._tag.geometry.getVertices2d();
30751         for (var i = 0; i < vertices2d.length - 1; i++) {
30752             if (isRect &&
30753                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
30754                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
30755                 continue;
30756             }
30757             var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
30758             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
30759             if (vertexCanvas == null) {
30760                 continue;
30761             }
30762             var cursor = isRect ?
30763                 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
30764                 "crosshair";
30765             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
30766             var vertexCanvasX = Math.round(vertexCanvas[0]);
30767             var vertexCanvasY = Math.round(vertexCanvas[1]);
30768             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
30769             var properties = {
30770                 onmousedown: interact,
30771                 style: { background: lineColor, transform: transform, cursor: cursor },
30772             };
30773             vNodes.push(vd.h("div.TagResizer", properties, []));
30774             if (!this._tag.indicateVertices) {
30775                 continue;
30776             }
30777             var pointProperties = {
30778                 style: { background: lineColor, transform: transform },
30779             };
30780             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
30781         }
30782         return vNodes;
30783     };
30784     OutlineRenderTag.prototype.getGLObjects = function () {
30785         var glObjects = [];
30786         if (this._fill != null) {
30787             glObjects.push(this._fill);
30788         }
30789         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
30790             var hole = _a[_i];
30791             glObjects.push(hole);
30792         }
30793         if (this._outline != null) {
30794             glObjects.push(this._outline);
30795         }
30796         return glObjects;
30797     };
30798     OutlineRenderTag.prototype.getRetrievableObjects = function () {
30799         return this._fill != null ? [this._fill] : [];
30800     };
30801     OutlineRenderTag.prototype._colorToCss = function (color) {
30802         return "#" + ("000000" + color.toString(16)).substr(-6);
30803     };
30804     OutlineRenderTag.prototype._createFill = function () {
30805         var triangles = this._tag.geometry.getTriangles3d(this._transform);
30806         var positions = new Float32Array(triangles);
30807         var geometry = new THREE.BufferGeometry();
30808         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
30809         geometry.computeBoundingSphere();
30810         var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
30811         this._updateFillMaterial(material);
30812         return new THREE.Mesh(geometry, material);
30813     };
30814     OutlineRenderTag.prototype._createHoles = function () {
30815         var holes = [];
30816         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
30817             var polygonGeometry = this._tag.geometry;
30818             var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
30819             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
30820                 var holePoints3d = holes3d_1[_i];
30821                 var hole = this._createLine(holePoints3d);
30822                 holes.push(hole);
30823             }
30824         }
30825         return holes;
30826     };
30827     OutlineRenderTag.prototype._createLine = function (points3d) {
30828         var positions = this._getLinePositions(points3d);
30829         var geometry = new THREE.BufferGeometry();
30830         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
30831         geometry.computeBoundingSphere();
30832         var material = new THREE.LineBasicMaterial();
30833         this._updateLineBasicMaterial(material);
30834         var line = new THREE.Line(geometry, material);
30835         line.renderOrder = 1;
30836         return line;
30837     };
30838     OutlineRenderTag.prototype._createOutline = function () {
30839         var points3d = this._tag.geometry.getPoints3d(this._transform);
30840         return this._createLine(points3d);
30841     };
30842     OutlineRenderTag.prototype._disposeFill = function () {
30843         if (this._fill == null) {
30844             return;
30845         }
30846         this._fill.geometry.dispose();
30847         this._fill.material.dispose();
30848         this._fill = null;
30849     };
30850     OutlineRenderTag.prototype._disposeHoles = function () {
30851         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
30852             var hole = _a[_i];
30853             hole.geometry.dispose();
30854             hole.material.dispose();
30855         }
30856         this._holes = [];
30857     };
30858     OutlineRenderTag.prototype._disposeOutline = function () {
30859         if (this._outline == null) {
30860             return;
30861         }
30862         this._outline.geometry.dispose();
30863         this._outline.material.dispose();
30864         this._outline = null;
30865     };
30866     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
30867         var length = points3d.length;
30868         var positions = new Float32Array(length * 3);
30869         for (var i = 0; i < length; ++i) {
30870             var index = 3 * i;
30871             var position = points3d[i];
30872             positions[index + 0] = position[0];
30873             positions[index + 1] = position[1];
30874             positions[index + 2] = position[2];
30875         }
30876         return positions;
30877     };
30878     OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
30879         var _this = this;
30880         return function (e) {
30881             var offsetX = e.offsetX - e.target.offsetWidth / 2;
30882             var offsetY = e.offsetY - e.target.offsetHeight / 2;
30883             _this._interact$.next({
30884                 cursor: cursor,
30885                 offsetX: offsetX,
30886                 offsetY: offsetY,
30887                 operation: operation,
30888                 tag: _this._tag,
30889                 vertexIndex: vertexIndex,
30890             });
30891         };
30892     };
30893     OutlineRenderTag.prototype._updateFillGeometry = function () {
30894         var triangles = this._tag.geometry.getTriangles3d(this._transform);
30895         var positions = new Float32Array(triangles);
30896         var geometry = this._fill.geometry;
30897         var attribute = geometry.getAttribute("position");
30898         if (attribute.array.length === positions.length) {
30899             attribute.set(positions);
30900             attribute.needsUpdate = true;
30901         }
30902         else {
30903             geometry.removeAttribute("position");
30904             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
30905         }
30906         geometry.computeBoundingSphere();
30907     };
30908     OutlineRenderTag.prototype._updateFillMaterial = function (material) {
30909         material.color = new THREE.Color(this._tag.fillColor);
30910         material.opacity = this._tag.fillOpacity;
30911         material.needsUpdate = true;
30912     };
30913     OutlineRenderTag.prototype._updateHoleGeometries = function () {
30914         var polygonGeometry = this._tag.geometry;
30915         var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
30916         if (holes3d.length !== this._holes.length) {
30917             throw new Error("Changing the number of holes is not supported.");
30918         }
30919         for (var i = 0; i < this._holes.length; i++) {
30920             var holePoints3d = holes3d[i];
30921             var hole = this._holes[i];
30922             this._updateLine(hole, holePoints3d);
30923         }
30924     };
30925     OutlineRenderTag.prototype._updateHoleMaterials = function () {
30926         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
30927             var hole = _a[_i];
30928             var material = hole.material;
30929             this._updateLineBasicMaterial(material);
30930         }
30931     };
30932     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
30933         var positions = this._getLinePositions(points3d);
30934         var geometry = line.geometry;
30935         var attribute = geometry.getAttribute("position");
30936         attribute.set(positions);
30937         attribute.needsUpdate = true;
30938         geometry.computeBoundingSphere();
30939     };
30940     OutlineRenderTag.prototype._updateOulineGeometry = function () {
30941         var points3d = this._tag.geometry.getPoints3d(this._transform);
30942         this._updateLine(this._outline, points3d);
30943     };
30944     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
30945         var material = this._outline.material;
30946         this._updateLineBasicMaterial(material);
30947     };
30948     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
30949         material.color = new THREE.Color(this._tag.lineColor);
30950         material.linewidth = Math.max(this._tag.lineWidth, 1);
30951         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
30952         material.opacity = this._tag.lineOpacity;
30953         material.transparent = this._tag.lineOpacity < 1;
30954         material.needsUpdate = true;
30955     };
30956     return OutlineRenderTag;
30957 }(Component_1.RenderTag));
30958 exports.OutlineRenderTag = OutlineRenderTag;
30959
30960 },{"../../../Component":230,"three":180,"virtual-dom":186}],315:[function(require,module,exports){
30961 "use strict";
30962 var __extends = (this && this.__extends) || (function () {
30963     var extendStatics = Object.setPrototypeOf ||
30964         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30965         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30966     return function (d, b) {
30967         extendStatics(d, b);
30968         function __() { this.constructor = d; }
30969         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30970     };
30971 })();
30972 Object.defineProperty(exports, "__esModule", { value: true });
30973 var Subject_1 = require("rxjs/Subject");
30974 var Component_1 = require("../../../Component");
30975 var Viewer_1 = require("../../../Viewer");
30976 /**
30977  * @class OutlineTag
30978  *
30979  * @classdesc Tag holding properties for visualizing a geometry outline.
30980  *
30981  * @example
30982  * ```
30983  * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
30984  * var tag = new Mapillary.TagComponent.OutlineTag(
30985  *     "id-1",
30986  *     geometry
30987  *     { editable: true, lineColor: 0xff0000 });
30988  *
30989  * tagComponent.add([tag]);
30990  * ```
30991  */
30992 var OutlineTag = (function (_super) {
30993     __extends(OutlineTag, _super);
30994     /**
30995      * Create an outline tag.
30996      *
30997      * @override
30998      * @constructor
30999      * @param {string} id - Unique identifier of the tag.
31000      * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
31001      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
31002      * behavior of the outline tag.
31003      */
31004     function OutlineTag(id, geometry, options) {
31005         var _this = _super.call(this, id, geometry) || this;
31006         options = !!options ? options : {};
31007         _this._editable = options.editable == null ? false : options.editable;
31008         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
31009         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
31010         _this._icon = options.icon === undefined ? null : options.icon;
31011         _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
31012         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
31013         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
31014         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
31015         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
31016         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
31017         _this._text = options.text === undefined ? null : options.text;
31018         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
31019         _this._click$ = new Subject_1.Subject();
31020         _this._click$
31021             .subscribe(function (t) {
31022             _this.fire(OutlineTag.click, _this);
31023         });
31024         return _this;
31025     }
31026     Object.defineProperty(OutlineTag.prototype, "click$", {
31027         /**
31028          * Click observable.
31029          *
31030          * @description An observable emitting the tag when the icon of the
31031          * tag has been clicked.
31032          *
31033          * @returns {Observable<Tag>}
31034          */
31035         get: function () {
31036             return this._click$;
31037         },
31038         enumerable: true,
31039         configurable: true
31040     });
31041     Object.defineProperty(OutlineTag.prototype, "editable", {
31042         /**
31043          * Get editable property.
31044          * @returns {boolean} Value indicating if tag is editable.
31045          */
31046         get: function () {
31047             return this._editable;
31048         },
31049         /**
31050          * Set editable property.
31051          * @param {boolean}
31052          *
31053          * @fires Tag#changed
31054          */
31055         set: function (value) {
31056             this._editable = value;
31057             this._notifyChanged$.next(this);
31058         },
31059         enumerable: true,
31060         configurable: true
31061     });
31062     Object.defineProperty(OutlineTag.prototype, "fillColor", {
31063         /**
31064          * Get fill color property.
31065          * @returns {number}
31066          */
31067         get: function () {
31068             return this._fillColor;
31069         },
31070         /**
31071          * Set fill color property.
31072          * @param {number}
31073          *
31074          * @fires Tag#changed
31075          */
31076         set: function (value) {
31077             this._fillColor = value;
31078             this._notifyChanged$.next(this);
31079         },
31080         enumerable: true,
31081         configurable: true
31082     });
31083     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
31084         /**
31085          * Get fill opacity property.
31086          * @returns {number}
31087          */
31088         get: function () {
31089             return this._fillOpacity;
31090         },
31091         /**
31092          * Set fill opacity property.
31093          * @param {number}
31094          *
31095          * @fires Tag#changed
31096          */
31097         set: function (value) {
31098             this._fillOpacity = value;
31099             this._notifyChanged$.next(this);
31100         },
31101         enumerable: true,
31102         configurable: true
31103     });
31104     Object.defineProperty(OutlineTag.prototype, "geometry", {
31105         /** @inheritdoc */
31106         get: function () {
31107             return this._geometry;
31108         },
31109         enumerable: true,
31110         configurable: true
31111     });
31112     Object.defineProperty(OutlineTag.prototype, "icon", {
31113         /**
31114          * Get icon property.
31115          * @returns {string}
31116          */
31117         get: function () {
31118             return this._icon;
31119         },
31120         /**
31121          * Set icon property.
31122          * @param {string}
31123          *
31124          * @fires Tag#changed
31125          */
31126         set: function (value) {
31127             this._icon = value;
31128             this._notifyChanged$.next(this);
31129         },
31130         enumerable: true,
31131         configurable: true
31132     });
31133     Object.defineProperty(OutlineTag.prototype, "iconFloat", {
31134         /**
31135          * Get icon float property.
31136          * @returns {Alignment}
31137          */
31138         get: function () {
31139             return this._iconFloat;
31140         },
31141         /**
31142          * Set icon float property.
31143          * @param {Alignment}
31144          *
31145          * @fires Tag#changed
31146          */
31147         set: function (value) {
31148             this._iconFloat = value;
31149             this._notifyChanged$.next(this);
31150         },
31151         enumerable: true,
31152         configurable: true
31153     });
31154     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
31155         /**
31156          * Get icon index property.
31157          * @returns {number}
31158          */
31159         get: function () {
31160             return this._iconIndex;
31161         },
31162         /**
31163          * Set icon index property.
31164          * @param {number}
31165          *
31166          * @fires Tag#changed
31167          */
31168         set: function (value) {
31169             this._iconIndex = value;
31170             this._notifyChanged$.next(this);
31171         },
31172         enumerable: true,
31173         configurable: true
31174     });
31175     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
31176         /**
31177          * Get indicate vertices property.
31178          * @returns {boolean} Value indicating if vertices should be indicated
31179          * when tag is editable.
31180          */
31181         get: function () {
31182             return this._indicateVertices;
31183         },
31184         /**
31185          * Set indicate vertices property.
31186          * @param {boolean}
31187          *
31188          * @fires Tag#changed
31189          */
31190         set: function (value) {
31191             this._indicateVertices = value;
31192             this._notifyChanged$.next(this);
31193         },
31194         enumerable: true,
31195         configurable: true
31196     });
31197     Object.defineProperty(OutlineTag.prototype, "lineColor", {
31198         /**
31199          * Get line color property.
31200          * @returns {number}
31201          */
31202         get: function () {
31203             return this._lineColor;
31204         },
31205         /**
31206          * Set line color property.
31207          * @param {number}
31208          *
31209          * @fires Tag#changed
31210          */
31211         set: function (value) {
31212             this._lineColor = value;
31213             this._notifyChanged$.next(this);
31214         },
31215         enumerable: true,
31216         configurable: true
31217     });
31218     Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
31219         /**
31220          * Get line opacity property.
31221          * @returns {number}
31222          */
31223         get: function () {
31224             return this._lineOpacity;
31225         },
31226         /**
31227          * Set line opacity property.
31228          * @param {number}
31229          *
31230          * @fires Tag#changed
31231          */
31232         set: function (value) {
31233             this._lineOpacity = value;
31234             this._notifyChanged$.next(this);
31235         },
31236         enumerable: true,
31237         configurable: true
31238     });
31239     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
31240         /**
31241          * Get line width property.
31242          * @returns {number}
31243          */
31244         get: function () {
31245             return this._lineWidth;
31246         },
31247         /**
31248          * Set line width property.
31249          * @param {number}
31250          *
31251          * @fires Tag#changed
31252          */
31253         set: function (value) {
31254             this._lineWidth = value;
31255             this._notifyChanged$.next(this);
31256         },
31257         enumerable: true,
31258         configurable: true
31259     });
31260     Object.defineProperty(OutlineTag.prototype, "text", {
31261         /**
31262          * Get text property.
31263          * @returns {string}
31264          */
31265         get: function () {
31266             return this._text;
31267         },
31268         /**
31269          * Set text property.
31270          * @param {string}
31271          *
31272          * @fires Tag#changed
31273          */
31274         set: function (value) {
31275             this._text = value;
31276             this._notifyChanged$.next(this);
31277         },
31278         enumerable: true,
31279         configurable: true
31280     });
31281     Object.defineProperty(OutlineTag.prototype, "textColor", {
31282         /**
31283          * Get text color property.
31284          * @returns {number}
31285          */
31286         get: function () {
31287             return this._textColor;
31288         },
31289         /**
31290          * Set text color property.
31291          * @param {number}
31292          *
31293          * @fires Tag#changed
31294          */
31295         set: function (value) {
31296             this._textColor = value;
31297             this._notifyChanged$.next(this);
31298         },
31299         enumerable: true,
31300         configurable: true
31301     });
31302     /**
31303      * Set options for tag.
31304      *
31305      * @description Sets all the option properties provided and keeps
31306      * the rest of the values as is.
31307      *
31308      * @param {IOutlineTagOptions} options - Outline tag options
31309      *
31310      * @fires {Tag#changed}
31311      */
31312     OutlineTag.prototype.setOptions = function (options) {
31313         this._editable = options.editable == null ? this._editable : options.editable;
31314         this._icon = options.icon === undefined ? this._icon : options.icon;
31315         this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
31316         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
31317         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
31318         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
31319         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
31320         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
31321         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
31322         this._text = options.text === undefined ? this._text : options.text;
31323         this._textColor = options.textColor == null ? this._textColor : options.textColor;
31324         this._notifyChanged$.next(this);
31325     };
31326     /**
31327      * Event fired when the icon of the outline tag is clicked.
31328      *
31329      * @event OutlineTag#click
31330      * @type {OutlineTag} The tag instance that was clicked.
31331      */
31332     OutlineTag.click = "click";
31333     return OutlineTag;
31334 }(Component_1.Tag));
31335 exports.OutlineTag = OutlineTag;
31336 exports.default = OutlineTag;
31337
31338 },{"../../../Component":230,"../../../Viewer":241,"rxjs/Subject":34}],316:[function(require,module,exports){
31339 "use strict";
31340 /// <reference path="../../../../typings/index.d.ts" />
31341 Object.defineProperty(exports, "__esModule", { value: true });
31342 var Subject_1 = require("rxjs/Subject");
31343 var Geo_1 = require("../../../Geo");
31344 var RenderTag = (function () {
31345     function RenderTag(tag, transform, viewportCoords) {
31346         this._tag = tag;
31347         this._transform = transform;
31348         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
31349         this._glObjectsChanged$ = new Subject_1.Subject();
31350         this._interact$ = new Subject_1.Subject();
31351     }
31352     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
31353         get: function () {
31354             return this._glObjectsChanged$;
31355         },
31356         enumerable: true,
31357         configurable: true
31358     });
31359     Object.defineProperty(RenderTag.prototype, "interact$", {
31360         get: function () {
31361             return this._interact$;
31362         },
31363         enumerable: true,
31364         configurable: true
31365     });
31366     Object.defineProperty(RenderTag.prototype, "tag", {
31367         get: function () {
31368             return this._tag;
31369         },
31370         enumerable: true,
31371         configurable: true
31372     });
31373     return RenderTag;
31374 }());
31375 exports.RenderTag = RenderTag;
31376 exports.default = RenderTag;
31377
31378 },{"../../../Geo":233,"rxjs/Subject":34}],317:[function(require,module,exports){
31379 "use strict";
31380 /// <reference path="../../../../typings/index.d.ts" />
31381 var __extends = (this && this.__extends) || (function () {
31382     var extendStatics = Object.setPrototypeOf ||
31383         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31384         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31385     return function (d, b) {
31386         extendStatics(d, b);
31387         function __() { this.constructor = d; }
31388         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31389     };
31390 })();
31391 Object.defineProperty(exports, "__esModule", { value: true });
31392 var vd = require("virtual-dom");
31393 var Component_1 = require("../../../Component");
31394 var Viewer_1 = require("../../../Viewer");
31395 /**
31396  * @class SpotRenderTag
31397  * @classdesc Tag visualizing the properties of a SpotTag.
31398  */
31399 var SpotRenderTag = (function (_super) {
31400     __extends(SpotRenderTag, _super);
31401     function SpotRenderTag() {
31402         return _super !== null && _super.apply(this, arguments) || this;
31403     }
31404     SpotRenderTag.prototype.dispose = function () { };
31405     SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
31406         var _this = this;
31407         var tag = this._tag;
31408         var container = {
31409             offsetHeight: size.height, offsetWidth: size.width,
31410         };
31411         var vNodes = [];
31412         var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
31413         var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
31414         if (centroidCanvas != null) {
31415             var interactNone = function (e) {
31416                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
31417             };
31418             var canvasX = Math.round(centroidCanvas[0]);
31419             var canvasY = Math.round(centroidCanvas[1]);
31420             if (tag.icon != null) {
31421                 if (atlas.loaded) {
31422                     var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
31423                     var transform_1 = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
31424                     var properties = {
31425                         onmousedown: interactNone,
31426                         style: {
31427                             pointerEvents: "all",
31428                             transform: transform_1,
31429                         },
31430                     };
31431                     vNodes.push(vd.h("div", properties, [sprite]));
31432                 }
31433             }
31434             else if (tag.text != null) {
31435                 var transform_2 = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
31436                 var properties = {
31437                     onmousedown: interactNone,
31438                     style: {
31439                         color: this._colorToCss(tag.textColor),
31440                         transform: transform_2,
31441                     },
31442                     textContent: tag.text,
31443                 };
31444                 vNodes.push(vd.h("span.TagSymbol", properties, []));
31445             }
31446             var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
31447             var background = this._colorToCss(tag.color);
31448             var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
31449             if (tag.editable) {
31450                 var interactorProperties = {
31451                     onmousedown: interact,
31452                     style: {
31453                         background: background,
31454                         transform: transform,
31455                     },
31456                 };
31457                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
31458             }
31459             var pointProperties = {
31460                 style: {
31461                     background: background,
31462                     transform: transform,
31463                 },
31464             };
31465             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
31466         }
31467         return vNodes;
31468     };
31469     SpotRenderTag.prototype.getGLObjects = function () { return []; };
31470     SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
31471     SpotRenderTag.prototype._colorToCss = function (color) {
31472         return "#" + ("000000" + color.toString(16)).substr(-6);
31473     };
31474     SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
31475         var _this = this;
31476         return function (e) {
31477             var offsetX = e.offsetX - e.target.offsetWidth / 2;
31478             var offsetY = e.offsetY - e.target.offsetHeight / 2;
31479             _this._interact$.next({
31480                 cursor: cursor,
31481                 offsetX: offsetX,
31482                 offsetY: offsetY,
31483                 operation: operation,
31484                 tag: tag,
31485                 vertexIndex: vertexIndex,
31486             });
31487         };
31488     };
31489     return SpotRenderTag;
31490 }(Component_1.RenderTag));
31491 exports.SpotRenderTag = SpotRenderTag;
31492
31493 },{"../../../Component":230,"../../../Viewer":241,"virtual-dom":186}],318:[function(require,module,exports){
31494 "use strict";
31495 var __extends = (this && this.__extends) || (function () {
31496     var extendStatics = Object.setPrototypeOf ||
31497         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31498         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31499     return function (d, b) {
31500         extendStatics(d, b);
31501         function __() { this.constructor = d; }
31502         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31503     };
31504 })();
31505 Object.defineProperty(exports, "__esModule", { value: true });
31506 var Component_1 = require("../../../Component");
31507 /**
31508  * @class SpotTag
31509  *
31510  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
31511  *
31512  * @example
31513  * ```
31514  * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
31515  * var tag = new Mapillary.TagComponent.SpotTag(
31516  *     "id-1",
31517  *     geometry
31518  *     { editable: true, color: 0xff0000 });
31519  *
31520  * tagComponent.add([tag]);
31521  * ```
31522  */
31523 var SpotTag = (function (_super) {
31524     __extends(SpotTag, _super);
31525     /**
31526      * Create a spot tag.
31527      *
31528      * @override
31529      * @constructor
31530      * @param {string} id
31531      * @param {Geometry} geometry
31532      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
31533      * behavior of the spot tag.
31534      */
31535     function SpotTag(id, geometry, options) {
31536         var _this = _super.call(this, id, geometry) || this;
31537         options = !!options ? options : {};
31538         _this._color = options.color == null ? 0xFFFFFF : options.color;
31539         _this._editable = options.editable == null ? false : options.editable;
31540         _this._icon = options.icon === undefined ? null : options.icon;
31541         _this._text = options.text === undefined ? null : options.text;
31542         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
31543         return _this;
31544     }
31545     Object.defineProperty(SpotTag.prototype, "color", {
31546         /**
31547          * Get color property.
31548          * @returns {number} The color of the spot as a hexagonal number;
31549          */
31550         get: function () {
31551             return this._color;
31552         },
31553         /**
31554          * Set color property.
31555          * @param {number}
31556          *
31557          * @fires Tag#changed
31558          */
31559         set: function (value) {
31560             this._color = value;
31561             this._notifyChanged$.next(this);
31562         },
31563         enumerable: true,
31564         configurable: true
31565     });
31566     Object.defineProperty(SpotTag.prototype, "editable", {
31567         /**
31568          * Get editable property.
31569          * @returns {boolean} Value indicating if tag is editable.
31570          */
31571         get: function () {
31572             return this._editable;
31573         },
31574         /**
31575          * Set editable property.
31576          * @param {boolean}
31577          *
31578          * @fires Tag#changed
31579          */
31580         set: function (value) {
31581             this._editable = value;
31582             this._notifyChanged$.next(this);
31583         },
31584         enumerable: true,
31585         configurable: true
31586     });
31587     Object.defineProperty(SpotTag.prototype, "icon", {
31588         /**
31589          * Get icon property.
31590          * @returns {string}
31591          */
31592         get: function () {
31593             return this._icon;
31594         },
31595         /**
31596          * Set icon property.
31597          * @param {string}
31598          *
31599          * @fires Tag#changed
31600          */
31601         set: function (value) {
31602             this._icon = value;
31603             this._notifyChanged$.next(this);
31604         },
31605         enumerable: true,
31606         configurable: true
31607     });
31608     Object.defineProperty(SpotTag.prototype, "text", {
31609         /**
31610          * Get text property.
31611          * @returns {string}
31612          */
31613         get: function () {
31614             return this._text;
31615         },
31616         /**
31617          * Set text property.
31618          * @param {string}
31619          *
31620          * @fires Tag#changed
31621          */
31622         set: function (value) {
31623             this._text = value;
31624             this._notifyChanged$.next(this);
31625         },
31626         enumerable: true,
31627         configurable: true
31628     });
31629     Object.defineProperty(SpotTag.prototype, "textColor", {
31630         /**
31631          * Get text color property.
31632          * @returns {number}
31633          */
31634         get: function () {
31635             return this._textColor;
31636         },
31637         /**
31638          * Set text color property.
31639          * @param {number}
31640          *
31641          * @fires Tag#changed
31642          */
31643         set: function (value) {
31644             this._textColor = value;
31645             this._notifyChanged$.next(this);
31646         },
31647         enumerable: true,
31648         configurable: true
31649     });
31650     /**
31651      * Set options for tag.
31652      *
31653      * @description Sets all the option properties provided and keps
31654      * the rest of the values as is.
31655      *
31656      * @param {ISpotTagOptions} options - Spot tag options
31657      *
31658      * @fires {Tag#changed}
31659      */
31660     SpotTag.prototype.setOptions = function (options) {
31661         this._color = options.color == null ? this._color : options.color;
31662         this._editable = options.editable == null ? this._editable : options.editable;
31663         this._icon = options.icon === undefined ? this._icon : options.icon;
31664         this._text = options.text === undefined ? this._text : options.text;
31665         this._textColor = options.textColor == null ? this._textColor : options.textColor;
31666         this._notifyChanged$.next(this);
31667     };
31668     return SpotTag;
31669 }(Component_1.Tag));
31670 exports.SpotTag = SpotTag;
31671 exports.default = SpotTag;
31672
31673 },{"../../../Component":230}],319:[function(require,module,exports){
31674 "use strict";
31675 var __extends = (this && this.__extends) || (function () {
31676     var extendStatics = Object.setPrototypeOf ||
31677         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31678         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31679     return function (d, b) {
31680         extendStatics(d, b);
31681         function __() { this.constructor = d; }
31682         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31683     };
31684 })();
31685 Object.defineProperty(exports, "__esModule", { value: true });
31686 var Subject_1 = require("rxjs/Subject");
31687 require("rxjs/add/operator/map");
31688 require("rxjs/add/operator/share");
31689 var Utils_1 = require("../../../Utils");
31690 /**
31691  * @class Tag
31692  * @abstract
31693  * @classdesc Abstract class representing the basic functionality of for a tag.
31694  */
31695 var Tag = (function (_super) {
31696     __extends(Tag, _super);
31697     /**
31698      * Create a tag.
31699      *
31700      * @constructor
31701      * @param {string} id
31702      * @param {Geometry} geometry
31703      */
31704     function Tag(id, geometry) {
31705         var _this = _super.call(this) || this;
31706         _this._id = id;
31707         _this._geometry = geometry;
31708         _this._notifyChanged$ = new Subject_1.Subject();
31709         _this._notifyChanged$
31710             .subscribe(function (t) {
31711             _this.fire(Tag.changed, _this);
31712         });
31713         _this._geometry.changed$
31714             .subscribe(function (g) {
31715             _this.fire(Tag.geometrychanged, _this);
31716         });
31717         return _this;
31718     }
31719     Object.defineProperty(Tag.prototype, "id", {
31720         /**
31721          * Get id property.
31722          * @returns {string}
31723          */
31724         get: function () {
31725             return this._id;
31726         },
31727         enumerable: true,
31728         configurable: true
31729     });
31730     Object.defineProperty(Tag.prototype, "geometry", {
31731         /**
31732          * Get geometry property.
31733          * @returns {Geometry} The geometry of the tag.
31734          */
31735         get: function () {
31736             return this._geometry;
31737         },
31738         enumerable: true,
31739         configurable: true
31740     });
31741     Object.defineProperty(Tag.prototype, "changed$", {
31742         /**
31743          * Get changed observable.
31744          * @returns {Observable<Tag>}
31745          * @ignore
31746          */
31747         get: function () {
31748             return this._notifyChanged$;
31749         },
31750         enumerable: true,
31751         configurable: true
31752     });
31753     Object.defineProperty(Tag.prototype, "geometryChanged$", {
31754         /**
31755          * Get geometry changed observable.
31756          * @returns {Observable<Tag>}
31757          * @ignore
31758          */
31759         get: function () {
31760             var _this = this;
31761             return this._geometry.changed$
31762                 .map(function (geometry) {
31763                 return _this;
31764             })
31765                 .share();
31766         },
31767         enumerable: true,
31768         configurable: true
31769     });
31770     /**
31771      * Event fired when a property related to the visual appearance of the
31772      * tag has changed.
31773      *
31774      * @event Tag#changed
31775      * @type {Tag} The tag instance that has changed.
31776      */
31777     Tag.changed = "changed";
31778     /**
31779      * Event fired when the geometry of the tag has changed.
31780      *
31781      * @event Tag#geometrychanged
31782      * @type {Tag} The tag instance whose geometry has changed.
31783      */
31784     Tag.geometrychanged = "geometrychanged";
31785     return Tag;
31786 }(Utils_1.EventEmitter));
31787 exports.Tag = Tag;
31788 exports.default = Tag;
31789
31790 },{"../../../Utils":240,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/share":75}],320:[function(require,module,exports){
31791 "use strict";
31792 Object.defineProperty(exports, "__esModule", { value: true });
31793 var HandlerBase = (function () {
31794     function HandlerBase(component, container, navigator) {
31795         this._component = component;
31796         this._container = container;
31797         this._navigator = navigator;
31798         this._enabled = false;
31799     }
31800     Object.defineProperty(HandlerBase.prototype, "isEnabled", {
31801         /**
31802          * Returns a Boolean indicating whether the interaction is enabled.
31803          *
31804          * @returns {boolean} `true` if the interaction is enabled.
31805          */
31806         get: function () {
31807             return this._enabled;
31808         },
31809         enumerable: true,
31810         configurable: true
31811     });
31812     /**
31813      * Enables the interaction.
31814      *
31815      * @example ```<component-name>.<handler-name>.enable();```
31816      */
31817     HandlerBase.prototype.enable = function () {
31818         if (this._enabled || !this._component.activated) {
31819             return;
31820         }
31821         this._enable();
31822         this._enabled = true;
31823         this._component.configure(this._getConfiguration(true));
31824     };
31825     /**
31826      * Disables the interaction.
31827      *
31828      * @example ```<component-name>.<handler-name>.disable();```
31829      */
31830     HandlerBase.prototype.disable = function () {
31831         if (!this._enabled) {
31832             return;
31833         }
31834         this._disable();
31835         this._enabled = false;
31836         if (this._component.activated) {
31837             this._component.configure(this._getConfiguration(false));
31838         }
31839     };
31840     return HandlerBase;
31841 }());
31842 exports.HandlerBase = HandlerBase;
31843 exports.default = HandlerBase;
31844
31845 },{}],321:[function(require,module,exports){
31846 "use strict";
31847 var __extends = (this && this.__extends) || (function () {
31848     var extendStatics = Object.setPrototypeOf ||
31849         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31850         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31851     return function (d, b) {
31852         extendStatics(d, b);
31853         function __() { this.constructor = d; }
31854         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31855     };
31856 })();
31857 Object.defineProperty(exports, "__esModule", { value: true });
31858 var MapillaryError_1 = require("./MapillaryError");
31859 var ArgumentMapillaryError = (function (_super) {
31860     __extends(ArgumentMapillaryError, _super);
31861     function ArgumentMapillaryError(message) {
31862         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
31863         _this.name = "ArgumentMapillaryError";
31864         return _this;
31865     }
31866     return ArgumentMapillaryError;
31867 }(MapillaryError_1.MapillaryError));
31868 exports.ArgumentMapillaryError = ArgumentMapillaryError;
31869 exports.default = ArgumentMapillaryError;
31870
31871 },{"./MapillaryError":323}],322:[function(require,module,exports){
31872 "use strict";
31873 var __extends = (this && this.__extends) || (function () {
31874     var extendStatics = Object.setPrototypeOf ||
31875         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31876         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31877     return function (d, b) {
31878         extendStatics(d, b);
31879         function __() { this.constructor = d; }
31880         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31881     };
31882 })();
31883 Object.defineProperty(exports, "__esModule", { value: true });
31884 var MapillaryError_1 = require("./MapillaryError");
31885 var GraphMapillaryError = (function (_super) {
31886     __extends(GraphMapillaryError, _super);
31887     function GraphMapillaryError(message) {
31888         var _this = _super.call(this, message) || this;
31889         _this.name = "GraphMapillaryError";
31890         return _this;
31891     }
31892     return GraphMapillaryError;
31893 }(MapillaryError_1.MapillaryError));
31894 exports.GraphMapillaryError = GraphMapillaryError;
31895 exports.default = GraphMapillaryError;
31896
31897 },{"./MapillaryError":323}],323:[function(require,module,exports){
31898 "use strict";
31899 var __extends = (this && this.__extends) || (function () {
31900     var extendStatics = Object.setPrototypeOf ||
31901         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31902         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31903     return function (d, b) {
31904         extendStatics(d, b);
31905         function __() { this.constructor = d; }
31906         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31907     };
31908 })();
31909 Object.defineProperty(exports, "__esModule", { value: true });
31910 var MapillaryError = (function (_super) {
31911     __extends(MapillaryError, _super);
31912     function MapillaryError(message) {
31913         var _this = _super.call(this, message) || this;
31914         _this.name = "MapillaryError";
31915         return _this;
31916     }
31917     return MapillaryError;
31918 }(Error));
31919 exports.MapillaryError = MapillaryError;
31920 exports.default = MapillaryError;
31921
31922 },{}],324:[function(require,module,exports){
31923 "use strict";
31924 /// <reference path="../../typings/index.d.ts" />
31925 Object.defineProperty(exports, "__esModule", { value: true });
31926 var THREE = require("three");
31927 /**
31928  * @class Camera
31929  *
31930  * @classdesc Holds information about a camera.
31931  */
31932 var Camera = (function () {
31933     /**
31934      * Create a new camera instance.
31935      * @param {Transform} [transform] - Optional transform instance.
31936      */
31937     function Camera(transform) {
31938         if (transform != null) {
31939             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
31940             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
31941             this._up = transform.upVector();
31942             this._focal = this._getFocal(transform);
31943         }
31944         else {
31945             this._position = new THREE.Vector3(0, 0, 0);
31946             this._lookat = new THREE.Vector3(0, 0, 1);
31947             this._up = new THREE.Vector3(0, -1, 0);
31948             this._focal = 1;
31949         }
31950     }
31951     Object.defineProperty(Camera.prototype, "position", {
31952         /**
31953          * Get position.
31954          * @returns {THREE.Vector3} The position vector.
31955          */
31956         get: function () {
31957             return this._position;
31958         },
31959         enumerable: true,
31960         configurable: true
31961     });
31962     Object.defineProperty(Camera.prototype, "lookat", {
31963         /**
31964          * Get lookat.
31965          * @returns {THREE.Vector3} The lookat vector.
31966          */
31967         get: function () {
31968             return this._lookat;
31969         },
31970         enumerable: true,
31971         configurable: true
31972     });
31973     Object.defineProperty(Camera.prototype, "up", {
31974         /**
31975          * Get up.
31976          * @returns {THREE.Vector3} The up vector.
31977          */
31978         get: function () {
31979             return this._up;
31980         },
31981         enumerable: true,
31982         configurable: true
31983     });
31984     Object.defineProperty(Camera.prototype, "focal", {
31985         /**
31986          * Get focal.
31987          * @returns {number} The focal length.
31988          */
31989         get: function () {
31990             return this._focal;
31991         },
31992         /**
31993          * Set focal.
31994          */
31995         set: function (value) {
31996             this._focal = value;
31997         },
31998         enumerable: true,
31999         configurable: true
32000     });
32001     /**
32002      * Update this camera to the linearly interpolated value of two other cameras.
32003      *
32004      * @param {Camera} a - First camera.
32005      * @param {Camera} b - Second camera.
32006      * @param {number} alpha - Interpolation value on the interval [0, 1].
32007      */
32008     Camera.prototype.lerpCameras = function (a, b, alpha) {
32009         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
32010         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
32011         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
32012         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
32013     };
32014     /**
32015      * Copy the properties of another camera to this camera.
32016      *
32017      * @param {Camera} other - Another camera.
32018      */
32019     Camera.prototype.copy = function (other) {
32020         this._position.copy(other.position);
32021         this._lookat.copy(other.lookat);
32022         this._up.copy(other.up);
32023         this._focal = other.focal;
32024     };
32025     /**
32026      * Clone this camera.
32027      *
32028      * @returns {Camera} A camera with cloned properties equal to this camera.
32029      */
32030     Camera.prototype.clone = function () {
32031         var camera = new Camera();
32032         camera.position.copy(this._position);
32033         camera.lookat.copy(this._lookat);
32034         camera.up.copy(this._up);
32035         camera.focal = this._focal;
32036         return camera;
32037     };
32038     /**
32039      * Determine the distance between this camera and another camera.
32040      *
32041      * @param {Camera} other - Another camera.
32042      * @returns {number} The distance between the cameras.
32043      */
32044     Camera.prototype.diff = function (other) {
32045         var pd = this._position.distanceToSquared(other.position);
32046         var ld = this._lookat.distanceToSquared(other.lookat);
32047         var ud = this._up.distanceToSquared(other.up);
32048         var fd = 100 * Math.abs(this._focal - other.focal);
32049         return Math.max(pd, ld, ud, fd);
32050     };
32051     /**
32052      * Get the focal length based on the transform.
32053      *
32054      * @description Returns the focal length of the transform if gpano info is not available.
32055      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
32056      * the gpano information if available.
32057      *
32058      * @returns {number} Focal length.
32059      */
32060     Camera.prototype._getFocal = function (transform) {
32061         if (transform.gpano == null) {
32062             return transform.focal;
32063         }
32064         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
32065         var focal = 0.5 / Math.tan(vFov / 2);
32066         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
32067     };
32068     return Camera;
32069 }());
32070 exports.Camera = Camera;
32071
32072 },{"three":180}],325:[function(require,module,exports){
32073 "use strict";
32074 Object.defineProperty(exports, "__esModule", { value: true });
32075 /**
32076  * @class GeoCoords
32077  *
32078  * @classdesc Converts coordinates between the geodetic (WGS84),
32079  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
32080  * East, North, Up (ENU) reference frames.
32081  *
32082  * The WGS84 has latitude (degrees), longitude (degrees) and
32083  * altitude (meters) values.
32084  *
32085  * The ECEF Z-axis pierces the north pole and the
32086  * XY-axis defines the equatorial plane. The X-axis extends
32087  * from the geocenter to the intersection of the Equator and
32088  * the Greenwich Meridian. All values in meters.
32089  *
32090  * The WGS84 parameters are:
32091  *
32092  * a = 6378137
32093  * b = a * (1 - f)
32094  * f = 1 / 298.257223563
32095  * e = Math.sqrt((a^2 - b^2) / a^2)
32096  * e' = Math.sqrt((a^2 - b^2) / b^2)
32097  *
32098  * The WGS84 to ECEF conversion is performed using the following:
32099  *
32100  * X = (N - h) * cos(phi) * cos(lambda)
32101  * Y = (N + h) * cos(phi) * sin(lambda)
32102  * Z = (b^2 * N / a^2 + h) * sin(phi)
32103  *
32104  * where
32105  *
32106  * phi = latitude
32107  * lambda = longitude
32108  * h = height above ellipsoid (altitude)
32109  * N = Radius of curvature (meters)
32110  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
32111  *
32112  * The ECEF to WGS84 conversion is performed using the following:
32113  *
32114  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
32115  * lambda = arctan(Y / X)
32116  * h = p / cos(phi) - N
32117  *
32118  * where
32119  *
32120  * p = Math.sqrt(X^2 + Y^2)
32121  * theta = arctan(Z * a / p * b)
32122  *
32123  * In the ENU reference frame the x-axis points to the
32124  * East, the y-axis to the North and the z-axis Up. All values
32125  * in meters.
32126  *
32127  * The ECEF to ENU conversion is performed using the following:
32128  *
32129  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
32130  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
32131  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
32132  *
32133  * where
32134  *
32135  * phi_r = latitude of reference
32136  * lambda_r = longitude of reference
32137  * X_r, Y_r, Z_r = ECEF coordinates of reference
32138  *
32139  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
32140  *
32141  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
32142  * the first step for both conversions.
32143  */
32144 var GeoCoords = (function () {
32145     function GeoCoords() {
32146         this._wgs84a = 6378137.0;
32147         this._wgs84b = 6356752.31424518;
32148     }
32149     /**
32150      * Convert coordinates from geodetic (WGS84) reference to local topocentric
32151      * (ENU) reference.
32152      *
32153      * @param {number} lat Latitude in degrees.
32154      * @param {number} lon Longitude in degrees.
32155      * @param {number} alt Altitude in meters.
32156      * @param {number} refLat Reference latitude in degrees.
32157      * @param {number} refLon Reference longitude in degrees.
32158      * @param {number} refAlt Reference altitude in meters.
32159      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
32160      */
32161     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
32162         var ecef = this.geodeticToEcef(lat, lon, alt);
32163         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
32164     };
32165     /**
32166      * Convert coordinates from local topocentric (ENU) reference to
32167      * geodetic (WGS84) reference.
32168      *
32169      * @param {number} x Topocentric ENU coordinate in East direction.
32170      * @param {number} y Topocentric ENU coordinate in North direction.
32171      * @param {number} z Topocentric ENU coordinate in Up direction.
32172      * @param {number} refLat Reference latitude in degrees.
32173      * @param {number} refLon Reference longitude in degrees.
32174      * @param {number} refAlt Reference altitude in meters.
32175      * @returns {Array<number>} The latitude and longitude in degrees
32176      *                          as well as altitude in meters.
32177      */
32178     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
32179         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
32180         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
32181     };
32182     /**
32183      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
32184      * to local topocentric (ENU) reference.
32185      *
32186      * @param {number} X ECEF X-value.
32187      * @param {number} Y ECEF Y-value.
32188      * @param {number} Z ECEF Z-value.
32189      * @param {number} refLat Reference latitude in degrees.
32190      * @param {number} refLon Reference longitude in degrees.
32191      * @param {number} refAlt Reference altitude in meters.
32192      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
32193      * and Up directions respectively.
32194      */
32195     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
32196         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
32197         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
32198         refLat = refLat * Math.PI / 180.0;
32199         refLon = refLon * Math.PI / 180.0;
32200         var cosLat = Math.cos(refLat);
32201         var sinLat = Math.sin(refLat);
32202         var cosLon = Math.cos(refLon);
32203         var sinLon = Math.sin(refLon);
32204         var x = -sinLon * V[0] + cosLon * V[1];
32205         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
32206         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
32207         return [x, y, z];
32208     };
32209     /**
32210      * Convert coordinates from local topocentric (ENU) reference
32211      * to Earth-Centered, Earth-Fixed (ECEF) reference.
32212      *
32213      * @param {number} x Topocentric ENU coordinate in East direction.
32214      * @param {number} y Topocentric ENU coordinate in North direction.
32215      * @param {number} z Topocentric ENU coordinate in Up direction.
32216      * @param {number} refLat Reference latitude in degrees.
32217      * @param {number} refLon Reference longitude in degrees.
32218      * @param {number} refAlt Reference altitude in meters.
32219      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
32220      */
32221     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
32222         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
32223         refLat = refLat * Math.PI / 180.0;
32224         refLon = refLon * Math.PI / 180.0;
32225         var cosLat = Math.cos(refLat);
32226         var sinLat = Math.sin(refLat);
32227         var cosLon = Math.cos(refLon);
32228         var sinLon = Math.sin(refLon);
32229         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
32230         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
32231         var Z = cosLat * y + sinLat * z + refEcef[2];
32232         return [X, Y, Z];
32233     };
32234     /**
32235      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
32236      * Earth-Fixed (ECEF) reference.
32237      *
32238      * @param {number} lat Latitude in degrees.
32239      * @param {number} lon Longitude in degrees.
32240      * @param {number} alt Altitude in meters.
32241      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
32242      */
32243     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
32244         var a = this._wgs84a;
32245         var b = this._wgs84b;
32246         lat = lat * Math.PI / 180.0;
32247         lon = lon * Math.PI / 180.0;
32248         var cosLat = Math.cos(lat);
32249         var sinLat = Math.sin(lat);
32250         var cosLon = Math.cos(lon);
32251         var sinLon = Math.sin(lon);
32252         var a2 = a * a;
32253         var b2 = b * b;
32254         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
32255         var nhcl = (a2 * L + alt) * cosLat;
32256         var X = nhcl * cosLon;
32257         var Y = nhcl * sinLon;
32258         var Z = (b2 * L + alt) * sinLat;
32259         return [X, Y, Z];
32260     };
32261     /**
32262      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
32263      * to geodetic reference (WGS84).
32264      *
32265      * @param {number} X ECEF X-value.
32266      * @param {number} Y ECEF Y-value.
32267      * @param {number} Z ECEF Z-value.
32268      * @returns {Array<number>} The latitude and longitude in degrees
32269      *                          as well as altitude in meters.
32270      */
32271     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
32272         var a = this._wgs84a;
32273         var b = this._wgs84b;
32274         var a2 = a * a;
32275         var b2 = b * b;
32276         var a2mb2 = a2 - b2;
32277         var ea = Math.sqrt(a2mb2 / a2);
32278         var eb = Math.sqrt(a2mb2 / b2);
32279         var p = Math.sqrt(X * X + Y * Y);
32280         var theta = Math.atan2(Z * a, p * b);
32281         var sinTheta = Math.sin(theta);
32282         var cosTheta = Math.cos(theta);
32283         var lon = Math.atan2(Y, X);
32284         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
32285         var sinLat = Math.sin(lat);
32286         var cosLat = Math.cos(lat);
32287         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
32288         var alt = p / cosLat - N;
32289         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
32290     };
32291     return GeoCoords;
32292 }());
32293 exports.GeoCoords = GeoCoords;
32294 exports.default = GeoCoords;
32295
32296 },{}],326:[function(require,module,exports){
32297 "use strict";
32298 /// <reference path="../../typings/index.d.ts" />
32299 Object.defineProperty(exports, "__esModule", { value: true });
32300 var THREE = require("three");
32301 /**
32302  * @class Spatial
32303  *
32304  * @classdesc Provides methods for scalar, vector and matrix calculations.
32305  */
32306 var Spatial = (function () {
32307     function Spatial() {
32308         this._epsilon = 1e-9;
32309     }
32310     /**
32311      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
32312      * bearing (clockwise with origin at north or Y-axis).
32313      *
32314      * @param {number} phi - Azimuthal phi angle in radians.
32315      * @returns {number} Bearing in radians.
32316      */
32317     Spatial.prototype.azimuthalToBearing = function (phi) {
32318         return -phi + Math.PI / 2;
32319     };
32320     /**
32321      * Converts degrees to radians.
32322      *
32323      * @param {number} deg - Degrees.
32324      * @returns {number} Radians.
32325      */
32326     Spatial.prototype.degToRad = function (deg) {
32327         return Math.PI * deg / 180;
32328     };
32329     /**
32330      * Converts radians to degrees.
32331      *
32332      * @param {number} rad - Radians.
32333      * @returns {number} Degrees.
32334      */
32335     Spatial.prototype.radToDeg = function (rad) {
32336         return 180 * rad / Math.PI;
32337     };
32338     /**
32339      * Creates a rotation matrix from an angle-axis vector.
32340      *
32341      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
32342      * @returns {THREE.Matrix4} Rotation matrix.
32343      */
32344     Spatial.prototype.rotationMatrix = function (angleAxis) {
32345         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
32346         var angle = axis.length();
32347         if (angle > 0) {
32348             axis.normalize();
32349         }
32350         return new THREE.Matrix4().makeRotationAxis(axis, angle);
32351     };
32352     /**
32353      * Rotates a vector according to a angle-axis rotation vector.
32354      *
32355      * @param {Array<number>} vector - Vector to rotate.
32356      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
32357      * @returns {THREE.Vector3} Rotated vector.
32358      */
32359     Spatial.prototype.rotate = function (vector, angleAxis) {
32360         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
32361         var rotationMatrix = this.rotationMatrix(angleAxis);
32362         v.applyMatrix4(rotationMatrix);
32363         return v;
32364     };
32365     /**
32366      * Calculates the optical center from a rotation vector
32367      * on the angle-axis representation and a translation vector
32368      * according to C = -R^T t.
32369      *
32370      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
32371      * @param {Array<number>} translation - Translation vector.
32372      * @returns {THREE.Vector3} Optical center.
32373      */
32374     Spatial.prototype.opticalCenter = function (rotation, translation) {
32375         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
32376         var vector = [-translation[0], -translation[1], -translation[2]];
32377         return this.rotate(vector, angleAxis);
32378     };
32379     /**
32380      * Calculates the viewing direction from a rotation vector
32381      * on the angle-axis representation.
32382      *
32383      * @param {number[]} rotation - Angle-axis representation of a rotation.
32384      * @returns {THREE.Vector3} Viewing direction.
32385      */
32386     Spatial.prototype.viewingDirection = function (rotation) {
32387         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
32388         return this.rotate([0, 0, 1], angleAxis);
32389     };
32390     /**
32391      * Wrap a number on the interval [min, max].
32392      *
32393      * @param {number} value - Value to wrap.
32394      * @param {number} min - Lower endpoint of interval.
32395      * @param {number} max - Upper endpoint of interval.
32396      * @returns {number} The wrapped number.
32397      */
32398     Spatial.prototype.wrap = function (value, min, max) {
32399         if (max < min) {
32400             throw new Error("Invalid arguments: max must be larger than min.");
32401         }
32402         var interval = (max - min);
32403         while (value > max || value < min) {
32404             if (value > max) {
32405                 value = value - interval;
32406             }
32407             else if (value < min) {
32408                 value = value + interval;
32409             }
32410         }
32411         return value;
32412     };
32413     /**
32414      * Wrap an angle on the interval [-Pi, Pi].
32415      *
32416      * @param {number} angle - Value to wrap.
32417      * @returns {number} Wrapped angle.
32418      */
32419     Spatial.prototype.wrapAngle = function (angle) {
32420         return this.wrap(angle, -Math.PI, Math.PI);
32421     };
32422     /**
32423      * Limit the value to the interval [min, max] by changing the value to
32424      * the nearest available one when it is outside the interval.
32425      *
32426      * @param {number} value - Value to clamp.
32427      * @param {number} min - Minimum of the interval.
32428      * @param {number} max - Maximum of the interval.
32429      * @returns {number} Clamped value.
32430      */
32431     Spatial.prototype.clamp = function (value, min, max) {
32432         if (value < min) {
32433             return min;
32434         }
32435         if (value > max) {
32436             return max;
32437         }
32438         return value;
32439     };
32440     /**
32441      * Calculates the counter-clockwise angle from the first
32442      * vector (x1, y1)^T to the second (x2, y2)^T.
32443      *
32444      * @param {number} x1 - X coordinate of first vector.
32445      * @param {number} y1 - Y coordinate of first vector.
32446      * @param {number} x2 - X coordinate of second vector.
32447      * @param {number} y2 - Y coordinate of second vector.
32448      * @returns {number} Counter clockwise angle between the vectors.
32449      */
32450     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
32451         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
32452         return this.wrapAngle(angle);
32453     };
32454     /**
32455      * Calculates the minimum (absolute) angle change for rotation
32456      * from one angle to another on the [-Pi, Pi] interval.
32457      *
32458      * @param {number} angle1 - Start angle.
32459      * @param {number} angle2 - Destination angle.
32460      * @returns {number} Absolute angle change between angles.
32461      */
32462     Spatial.prototype.angleDifference = function (angle1, angle2) {
32463         var angle = angle2 - angle1;
32464         return this.wrapAngle(angle);
32465     };
32466     /**
32467      * Calculates the relative rotation angle between two
32468      * angle-axis vectors.
32469      *
32470      * @param {number} rotation1 - First angle-axis vector.
32471      * @param {number} rotation2 - Second angle-axis vector.
32472      * @returns {number} Relative rotation angle.
32473      */
32474     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
32475         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
32476         var R2 = this.rotationMatrix(rotation2);
32477         var R = R1T.multiply(R2);
32478         var elements = R.elements;
32479         // from Tr(R) = 1 + 2*cos(theta)
32480         var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
32481         return theta;
32482     };
32483     /**
32484      * Calculates the angle from a vector to a plane.
32485      *
32486      * @param {Array<number>} vector - The vector.
32487      * @param {Array<number>} planeNormal - Normal of the plane.
32488      * @returns {number} Angle from between plane and vector.
32489      */
32490     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
32491         var v = new THREE.Vector3().fromArray(vector);
32492         var norm = v.length();
32493         if (norm < this._epsilon) {
32494             return 0;
32495         }
32496         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
32497         return Math.asin(projection / norm);
32498     };
32499     /**
32500      * Calculates the distance between two coordinates
32501      * (latitude longitude pairs) in meters according to
32502      * the haversine formula.
32503      *
32504      * @param {number} lat1 - Latitude of the first coordinate.
32505      * @param {number} lon1 - Longitude of the first coordinate.
32506      * @param {number} lat2 - Latitude of the second coordinate.
32507      * @param {number} lon2 - Longitude of the second coordinate.
32508      * @returns {number} Distance between lat lon positions.
32509      */
32510     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
32511         var r = 6371000;
32512         var dLat = this.degToRad(lat2 - lat1);
32513         var dLon = this.degToRad(lon2 - lon1);
32514         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
32515             Math.cos(lat1) * Math.cos(lat2) *
32516                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
32517         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
32518         return d;
32519     };
32520     return Spatial;
32521 }());
32522 exports.Spatial = Spatial;
32523 exports.default = Spatial;
32524
32525 },{"three":180}],327:[function(require,module,exports){
32526 "use strict";
32527 /// <reference path="../../typings/index.d.ts" />
32528 Object.defineProperty(exports, "__esModule", { value: true });
32529 var THREE = require("three");
32530 /**
32531  * @class Transform
32532  *
32533  * @classdesc Class used for calculating coordinate transformations
32534  * and projections.
32535  */
32536 var Transform = (function () {
32537     /**
32538      * Create a new transform instance.
32539      * @param {Node} apiNavImIm - Node properties.
32540      * @param {HTMLImageElement} image - Node image.
32541      * @param {Array<number>} translation - Node translation vector in three dimensions.
32542      */
32543     function Transform(node, image, translation) {
32544         this._orientation = this._getValue(node.orientation, 1);
32545         var imageWidth = image != null ? image.width : 4;
32546         var imageHeight = image != null ? image.height : 3;
32547         var keepOrientation = this._orientation < 5;
32548         this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
32549         this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
32550         this._basicAspect = keepOrientation ?
32551             this._width / this._height :
32552             this._height / this._width;
32553         this._basicWidth = keepOrientation ? node.width : node.height;
32554         this._basicHeight = keepOrientation ? node.height : node.width;
32555         this._focal = this._getValue(node.focal, 1);
32556         this._scale = this._getValue(node.scale, 0);
32557         this._gpano = node.gpano != null ? node.gpano : null;
32558         this._rt = this._getRt(node.rotation, translation);
32559         this._srt = this._getSrt(this._rt, this._scale);
32560     }
32561     Object.defineProperty(Transform.prototype, "basicAspect", {
32562         /**
32563          * Get basic aspect.
32564          * @returns {number} The orientation adjusted aspect ratio.
32565          */
32566         get: function () {
32567             return this._basicAspect;
32568         },
32569         enumerable: true,
32570         configurable: true
32571     });
32572     Object.defineProperty(Transform.prototype, "basicHeight", {
32573         /**
32574          * Get basic height.
32575          *
32576          * @description Does not fall back to node image height but
32577          * uses original value from API so can be faulty.
32578          *
32579          * @returns {number} The height of the basic version image
32580          * (adjusted for orientation).
32581          */
32582         get: function () {
32583             return this._basicHeight;
32584         },
32585         enumerable: true,
32586         configurable: true
32587     });
32588     Object.defineProperty(Transform.prototype, "basicWidth", {
32589         /**
32590          * Get basic width.
32591          *
32592          * @description Does not fall back to node image width but
32593          * uses original value from API so can be faulty.
32594          *
32595          * @returns {number} The width of the basic version image
32596          * (adjusted for orientation).
32597          */
32598         get: function () {
32599             return this._basicWidth;
32600         },
32601         enumerable: true,
32602         configurable: true
32603     });
32604     Object.defineProperty(Transform.prototype, "focal", {
32605         /**
32606          * Get focal.
32607          * @returns {number} The node focal length.
32608          */
32609         get: function () {
32610             return this._focal;
32611         },
32612         enumerable: true,
32613         configurable: true
32614     });
32615     Object.defineProperty(Transform.prototype, "fullPano", {
32616         /**
32617          * Get fullPano.
32618          *
32619          * @returns {boolean} Value indicating whether the node is a complete
32620          * 360 panorama.
32621          */
32622         get: function () {
32623             return this._gpano != null &&
32624                 this._gpano.CroppedAreaLeftPixels === 0 &&
32625                 this._gpano.CroppedAreaTopPixels === 0 &&
32626                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
32627                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
32628         },
32629         enumerable: true,
32630         configurable: true
32631     });
32632     Object.defineProperty(Transform.prototype, "gpano", {
32633         /**
32634          * Get gpano.
32635          * @returns {number} The node gpano information.
32636          */
32637         get: function () {
32638             return this._gpano;
32639         },
32640         enumerable: true,
32641         configurable: true
32642     });
32643     Object.defineProperty(Transform.prototype, "height", {
32644         /**
32645          * Get height.
32646          *
32647          * @description Falls back to the node image height if
32648          * the API data is faulty.
32649          *
32650          * @returns {number} The orientation adjusted image height.
32651          */
32652         get: function () {
32653             return this._height;
32654         },
32655         enumerable: true,
32656         configurable: true
32657     });
32658     Object.defineProperty(Transform.prototype, "orientation", {
32659         /**
32660          * Get orientation.
32661          * @returns {number} The image orientation.
32662          */
32663         get: function () {
32664             return this._orientation;
32665         },
32666         enumerable: true,
32667         configurable: true
32668     });
32669     Object.defineProperty(Transform.prototype, "rt", {
32670         /**
32671          * Get rt.
32672          * @returns {THREE.Matrix4} The extrinsic camera matrix.
32673          */
32674         get: function () {
32675             return this._rt;
32676         },
32677         enumerable: true,
32678         configurable: true
32679     });
32680     Object.defineProperty(Transform.prototype, "srt", {
32681         /**
32682          * Get srt.
32683          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
32684          */
32685         get: function () {
32686             return this._srt;
32687         },
32688         enumerable: true,
32689         configurable: true
32690     });
32691     Object.defineProperty(Transform.prototype, "scale", {
32692         /**
32693          * Get scale.
32694          * @returns {number} The node atomic reconstruction scale.
32695          */
32696         get: function () {
32697             return this._scale;
32698         },
32699         enumerable: true,
32700         configurable: true
32701     });
32702     Object.defineProperty(Transform.prototype, "hasValidScale", {
32703         /**
32704          * Get has valid scale.
32705          * @returns {boolean} Value indicating if the scale of the transform is valid.
32706          */
32707         get: function () {
32708             return this._scale > 1e-2 && this._scale < 50;
32709         },
32710         enumerable: true,
32711         configurable: true
32712     });
32713     Object.defineProperty(Transform.prototype, "width", {
32714         /**
32715          * Get width.
32716          *
32717          * @description Falls back to the node image width if
32718          * the API data is faulty.
32719          *
32720          * @returns {number} The orientation adjusted image width.
32721          */
32722         get: function () {
32723             return this._width;
32724         },
32725         enumerable: true,
32726         configurable: true
32727     });
32728     /**
32729      * Calculate the up vector for the node transform.
32730      *
32731      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
32732      */
32733     Transform.prototype.upVector = function () {
32734         var rte = this._rt.elements;
32735         switch (this._orientation) {
32736             case 1:
32737                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
32738             case 3:
32739                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
32740             case 6:
32741                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
32742             case 8:
32743                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
32744             default:
32745                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
32746         }
32747     };
32748     /**
32749      * Calculate projector matrix for projecting 3D points to texture map
32750      * coordinates (u and v).
32751      *
32752      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
32753      * map coordinate calculations.
32754      */
32755     Transform.prototype.projectorMatrix = function () {
32756         var projector = this._normalizedToTextureMatrix();
32757         var f = this._focal;
32758         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
32759         projector.multiply(projection);
32760         projector.multiply(this._rt);
32761         return projector;
32762     };
32763     /**
32764      * Project 3D world coordinates to basic coordinates.
32765      *
32766      * @param {Array<number>} point3d - 3D world coordinates.
32767      * @return {Array<number>} 2D basic coordinates.
32768      */
32769     Transform.prototype.projectBasic = function (point3d) {
32770         var sfm = this.projectSfM(point3d);
32771         return this._sfmToBasic(sfm);
32772     };
32773     /**
32774      * Unproject basic coordinates to 3D world coordinates.
32775      *
32776      * @param {Array<number>} basic - 2D basic coordinates.
32777      * @param {Array<number>} distance - Depth to unproject from camera center.
32778      * @returns {Array<number>} Unprojected 3D world coordinates.
32779      */
32780     Transform.prototype.unprojectBasic = function (basic, distance) {
32781         var sfm = this._basicToSfm(basic);
32782         return this.unprojectSfM(sfm, distance);
32783     };
32784     /**
32785      * Project 3D world coordinates to SfM coordinates.
32786      *
32787      * @param {Array<number>} point3d - 3D world coordinates.
32788      * @return {Array<number>} 2D SfM coordinates.
32789      */
32790     Transform.prototype.projectSfM = function (point3d) {
32791         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
32792         v.applyMatrix4(this._rt);
32793         return this._bearingToSfm([v.x, v.y, v.z]);
32794     };
32795     /**
32796      * Unproject SfM coordinates to a 3D world coordinates.
32797      *
32798      * @param {Array<number>} sfm - 2D SfM coordinates.
32799      * @param {Array<number>} distance - Depth to unproject from camera center.
32800      * @returns {Array<number>} Unprojected 3D world coordinates.
32801      */
32802     Transform.prototype.unprojectSfM = function (sfm, distance) {
32803         var bearing = this._sfmToBearing(sfm);
32804         var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
32805         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
32806         return [v.x / v.w, v.y / v.w, v.z / v.w];
32807     };
32808     /**
32809      * Transform SfM coordinates to bearing vector (3D cartesian
32810      * coordinates on the unit sphere).
32811      *
32812      * @param {Array<number>} sfm - 2D SfM coordinates.
32813      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
32814      * on the unit sphere).
32815      */
32816     Transform.prototype._sfmToBearing = function (sfm) {
32817         if (this._fullPano()) {
32818             var lon = sfm[0] * 2 * Math.PI;
32819             var lat = -sfm[1] * 2 * Math.PI;
32820             var x = Math.cos(lat) * Math.sin(lon);
32821             var y = -Math.sin(lat);
32822             var z = Math.cos(lat) * Math.cos(lon);
32823             return [x, y, z];
32824         }
32825         else if (this._gpano) {
32826             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
32827             var fullPanoPixel = [
32828                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
32829                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
32830             ];
32831             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
32832             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
32833             var x = Math.cos(lat) * Math.sin(lon);
32834             var y = -Math.sin(lat);
32835             var z = Math.cos(lat) * Math.cos(lon);
32836             return [x, y, z];
32837         }
32838         else {
32839             var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
32840             v.normalize();
32841             return [v.x, v.y, v.z];
32842         }
32843     };
32844     /**
32845      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
32846      * SfM coordinates.
32847      *
32848      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
32849      * unit sphere).
32850      * @returns {Array<number>} 2D SfM coordinates.
32851      */
32852     Transform.prototype._bearingToSfm = function (bearing) {
32853         if (this._fullPano()) {
32854             var x = bearing[0];
32855             var y = bearing[1];
32856             var z = bearing[2];
32857             var lon = Math.atan2(x, z);
32858             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
32859             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
32860         }
32861         else if (this._gpano) {
32862             var x = bearing[0];
32863             var y = bearing[1];
32864             var z = bearing[2];
32865             var lon = Math.atan2(x, z);
32866             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
32867             var fullPanoPixel = [
32868                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
32869                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
32870             ];
32871             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
32872             return [
32873                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
32874                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
32875             ];
32876         }
32877         else {
32878             if (bearing[2] > 0) {
32879                 return [
32880                     bearing[0] * this._focal / bearing[2],
32881                     bearing[1] * this._focal / bearing[2],
32882                 ];
32883             }
32884             else {
32885                 return [
32886                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
32887                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
32888                 ];
32889             }
32890         }
32891     };
32892     /**
32893      * Convert basic coordinates to SfM coordinates.
32894      *
32895      * @param {Array<number>} basic - 2D basic coordinates.
32896      * @returns {Array<number>} 2D SfM coordinates.
32897      */
32898     Transform.prototype._basicToSfm = function (basic) {
32899         var rotatedX;
32900         var rotatedY;
32901         switch (this._orientation) {
32902             case 1:
32903                 rotatedX = basic[0];
32904                 rotatedY = basic[1];
32905                 break;
32906             case 3:
32907                 rotatedX = 1 - basic[0];
32908                 rotatedY = 1 - basic[1];
32909                 break;
32910             case 6:
32911                 rotatedX = basic[1];
32912                 rotatedY = 1 - basic[0];
32913                 break;
32914             case 8:
32915                 rotatedX = 1 - basic[1];
32916                 rotatedY = basic[0];
32917                 break;
32918             default:
32919                 rotatedX = basic[0];
32920                 rotatedY = basic[1];
32921                 break;
32922         }
32923         var w = this._width;
32924         var h = this._height;
32925         var s = Math.max(w, h);
32926         var sfmX = rotatedX * w / s - w / s / 2;
32927         var sfmY = rotatedY * h / s - h / s / 2;
32928         return [sfmX, sfmY];
32929     };
32930     /**
32931      * Convert SfM coordinates to basic coordinates.
32932      *
32933      * @param {Array<number>} sfm - 2D SfM coordinates.
32934      * @returns {Array<number>} 2D basic coordinates.
32935      */
32936     Transform.prototype._sfmToBasic = function (sfm) {
32937         var w = this._width;
32938         var h = this._height;
32939         var s = Math.max(w, h);
32940         var rotatedX = (sfm[0] + w / s / 2) / w * s;
32941         var rotatedY = (sfm[1] + h / s / 2) / h * s;
32942         var basicX;
32943         var basicY;
32944         switch (this._orientation) {
32945             case 1:
32946                 basicX = rotatedX;
32947                 basicY = rotatedY;
32948                 break;
32949             case 3:
32950                 basicX = 1 - rotatedX;
32951                 basicY = 1 - rotatedY;
32952                 break;
32953             case 6:
32954                 basicX = 1 - rotatedY;
32955                 basicY = rotatedX;
32956                 break;
32957             case 8:
32958                 basicX = rotatedY;
32959                 basicY = 1 - rotatedX;
32960                 break;
32961             default:
32962                 basicX = rotatedX;
32963                 basicY = rotatedY;
32964                 break;
32965         }
32966         return [basicX, basicY];
32967     };
32968     /**
32969      * Determines if the gpano information indicates a full panorama.
32970      *
32971      * @returns {boolean} Value determining if the gpano information indicates
32972      * a full panorama.
32973      */
32974     Transform.prototype._fullPano = function () {
32975         return this.gpano != null &&
32976             this.gpano.CroppedAreaLeftPixels === 0 &&
32977             this.gpano.CroppedAreaTopPixels === 0 &&
32978             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
32979             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
32980     };
32981     /**
32982      * Checks a value and returns it if it exists and is larger than 0.
32983      * Fallbacks if it is null.
32984      *
32985      * @param {number} value - Value to check.
32986      * @param {number} fallback - Value to fall back to.
32987      * @returns {number} The value or its fallback value if it is not defined or negative.
32988      */
32989     Transform.prototype._getValue = function (value, fallback) {
32990         return value != null && value > 0 ? value : fallback;
32991     };
32992     /**
32993      * Creates the extrinsic camera matrix [ R | t ].
32994      *
32995      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
32996      * @param {Array<number>} translation - Translation vector.
32997      * @returns {THREE.Matrix4} Extrisic camera matrix.
32998      */
32999     Transform.prototype._getRt = function (rotation, translation) {
33000         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
33001         var angle = axis.length();
33002         if (angle > 0) {
33003             axis.normalize();
33004         }
33005         var rt = new THREE.Matrix4();
33006         rt.makeRotationAxis(axis, angle);
33007         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
33008         return rt;
33009     };
33010     /**
33011      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
33012      *
33013      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
33014      * @param {number} scale - Scale factor.
33015      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
33016      */
33017     Transform.prototype._getSrt = function (rt, scale) {
33018         var srt = rt.clone();
33019         var elements = srt.elements;
33020         elements[12] = scale * elements[12];
33021         elements[13] = scale * elements[13];
33022         elements[14] = scale * elements[14];
33023         srt.scale(new THREE.Vector3(scale, scale, scale));
33024         return srt;
33025     };
33026     /**
33027      * Calculate a transformation matrix from normalized coordinates for
33028      * texture map coordinates.
33029      *
33030      * @returns {THREE.Matrix4} Normalized coordinates to texture map
33031      * coordinates transformation matrix.
33032      */
33033     Transform.prototype._normalizedToTextureMatrix = function () {
33034         var size = Math.max(this._width, this._height);
33035         var w = size / this._width;
33036         var h = size / this._height;
33037         switch (this._orientation) {
33038             case 1:
33039                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
33040             case 3:
33041                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
33042             case 6:
33043                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
33044             case 8:
33045                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
33046             default:
33047                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
33048         }
33049     };
33050     return Transform;
33051 }());
33052 exports.Transform = Transform;
33053
33054 },{"three":180}],328:[function(require,module,exports){
33055 "use strict";
33056 /// <reference path="../../typings/index.d.ts" />
33057 Object.defineProperty(exports, "__esModule", { value: true });
33058 var THREE = require("three");
33059 /**
33060  * @class ViewportCoords
33061  *
33062  * @classdesc Provides methods for calculating 2D coordinate conversions
33063  * as well as 3D projection and unprojection.
33064  *
33065  * Basic coordinates are 2D coordinates on the [0, 1] interval and
33066  * have the origin point, (0, 0), at the top left corner and the
33067  * maximum value, (1, 1), at the bottom right corner of the original
33068  * photo.
33069  *
33070  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
33071  * have the origin point in the center. The bottom left corner point is
33072  * (-1, -1) and the top right corner point is (1, 1).
33073  *
33074  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
33075  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
33076  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
33077  * bottom right corner.
33078  *
33079  * 3D coordinates are in the topocentric world reference frame.
33080  */
33081 var ViewportCoords = (function () {
33082     function ViewportCoords() {
33083         this._unprojectDepth = 200;
33084     }
33085     /**
33086      * Convert basic coordinates to canvas coordinates.
33087      *
33088      * @description Transform origin and camera position needs to be the
33089      * equal for reliable return value.
33090      *
33091      * @param {number} basicX - Basic X coordinate.
33092      * @param {number} basicY - Basic Y coordinate.
33093      * @param {HTMLElement} container - The viewer container.
33094      * @param {Transform} transform - Transform of the node to unproject from.
33095      * @param {THREE.Camera} camera - Camera used in rendering.
33096      * @returns {Array<number>} 2D canvas coordinates.
33097      */
33098     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
33099         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
33100         var canvas = this.projectToCanvas(point3d, container, camera);
33101         return canvas;
33102     };
33103     /**
33104      * Convert basic coordinates to canvas coordinates safely. If 3D point is
33105      * behind camera null will be returned.
33106      *
33107      * @description Transform origin and camera position needs to be the
33108      * equal for reliable return value.
33109      *
33110      * @param {number} basicX - Basic X coordinate.
33111      * @param {number} basicY - Basic Y coordinate.
33112      * @param {HTMLElement} container - The viewer container.
33113      * @param {Transform} transform - Transform of the node to unproject from.
33114      * @param {THREE.Camera} camera - Camera used in rendering.
33115      * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
33116      * in front of the camera, otherwise null.
33117      */
33118     ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
33119         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
33120         var pointCamera = this.worldToCamera(point3d, camera);
33121         if (pointCamera[2] > 0) {
33122             return null;
33123         }
33124         var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
33125         var canvas = this.viewportToCanvas(viewportX, viewportY, container);
33126         return canvas;
33127     };
33128     /**
33129      * Convert basic coordinates to viewport coordinates.
33130      *
33131      * @description Transform origin and camera position needs to be the
33132      * equal for reliable return value.
33133      *
33134      * @param {number} basicX - Basic X coordinate.
33135      * @param {number} basicY - Basic Y coordinate.
33136      * @param {Transform} transform - Transform of the node to unproject from.
33137      * @param {THREE.Camera} camera - Camera used in rendering.
33138      * @returns {Array<number>} 2D viewport coordinates.
33139      */
33140     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
33141         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
33142         var viewport = this.projectToViewport(point3d, camera);
33143         return viewport;
33144     };
33145     /**
33146      * Convert camera 3D coordinates to viewport coordinates.
33147      *
33148      * @param {number} pointCamera - 3D point in camera coordinate system.
33149      * @param {THREE.Camera} camera - Camera used in rendering.
33150      * @returns {Array<number>} 2D viewport coordinates.
33151      */
33152     ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
33153         var viewport = new THREE.Vector3().fromArray(pointCamera)
33154             .applyMatrix4(camera.projectionMatrix);
33155         return [viewport.x, viewport.y];
33156     };
33157     /**
33158      * Get canvas pixel position from event.
33159      *
33160      * @param {Event} event - Event containing clientX and clientY properties.
33161      * @param {HTMLElement} element - HTML element.
33162      * @returns {Array<number>} 2D canvas coordinates.
33163      */
33164     ViewportCoords.prototype.canvasPosition = function (event, element) {
33165         var clientRect = element.getBoundingClientRect();
33166         var canvasX = event.clientX - clientRect.left - element.clientLeft;
33167         var canvasY = event.clientY - clientRect.top - element.clientTop;
33168         return [canvasX, canvasY];
33169     };
33170     /**
33171      * Convert canvas coordinates to basic coordinates.
33172      *
33173      * @description Transform origin and camera position needs to be the
33174      * equal for reliable return value.
33175      *
33176      * @param {number} canvasX - Canvas X coordinate.
33177      * @param {number} canvasY - Canvas Y coordinate.
33178      * @param {HTMLElement} container - The viewer container.
33179      * @param {Transform} transform - Transform of the node to unproject from.
33180      * @param {THREE.Camera} camera - Camera used in rendering.
33181      * @returns {Array<number>} 2D basic coordinates.
33182      */
33183     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
33184         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
33185             .toArray();
33186         var basic = transform.projectBasic(point3d);
33187         return basic;
33188     };
33189     /**
33190      * Convert canvas coordinates to viewport coordinates.
33191      *
33192      * @param {number} canvasX - Canvas X coordinate.
33193      * @param {number} canvasY - Canvas Y coordinate.
33194      * @param {HTMLElement} container - The viewer container.
33195      * @returns {Array<number>} 2D viewport coordinates.
33196      */
33197     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
33198         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
33199         var viewportX = 2 * canvasX / canvasWidth - 1;
33200         var viewportY = 1 - 2 * canvasY / canvasHeight;
33201         return [viewportX, viewportY];
33202     };
33203     /**
33204      * Determines the width and height of the container in canvas coordinates.
33205      *
33206      * @param {HTMLElement} container - The viewer container.
33207      * @returns {Array<number>} 2D canvas coordinates.
33208      */
33209     ViewportCoords.prototype.containerToCanvas = function (container) {
33210         return [container.offsetWidth, container.offsetHeight];
33211     };
33212     /**
33213      * Determine basic distances from image to canvas corners.
33214      *
33215      * @description Transform origin and camera position needs to be the
33216      * equal for reliable return value.
33217      *
33218      * Determines the smallest basic distance for every side of the canvas.
33219      *
33220      * @param {Transform} transform - Transform of the node to unproject from.
33221      * @param {THREE.Camera} camera - Camera used in rendering.
33222      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
33223      */
33224     ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
33225         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
33226         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
33227         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
33228         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
33229         var topBasicDistance = 0;
33230         var rightBasicDistance = 0;
33231         var bottomBasicDistance = 0;
33232         var leftBasicDistance = 0;
33233         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
33234             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
33235                 -topLeftBasic[1] :
33236                 -topRightBasic[1];
33237         }
33238         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
33239             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
33240                 topRightBasic[0] - 1 :
33241                 bottomRightBasic[0] - 1;
33242         }
33243         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
33244             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
33245                 bottomRightBasic[1] - 1 :
33246                 bottomLeftBasic[1] - 1;
33247         }
33248         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
33249             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
33250                 -bottomLeftBasic[0] :
33251                 -topLeftBasic[0];
33252         }
33253         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
33254     };
33255     /**
33256      * Determine pixel distances from image to canvas corners.
33257      *
33258      * @description Transform origin and camera position needs to be the
33259      * equal for reliable return value.
33260      *
33261      * Determines the smallest pixel distance for every side of the canvas.
33262      *
33263      * @param {HTMLElement} container - The viewer container.
33264      * @param {Transform} transform - Transform of the node to unproject from.
33265      * @param {THREE.Camera} camera - Camera used in rendering.
33266      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
33267      */
33268     ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
33269         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
33270         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
33271         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
33272         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
33273         var topPixelDistance = 0;
33274         var rightPixelDistance = 0;
33275         var bottomPixelDistance = 0;
33276         var leftPixelDistance = 0;
33277         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
33278         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
33279             var basicX = topLeftBasic[1] > topRightBasic[1] ?
33280                 topLeftBasic[0] :
33281                 topRightBasic[0];
33282             var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
33283             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
33284         }
33285         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
33286             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
33287                 topRightBasic[1] :
33288                 bottomRightBasic[1];
33289             var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
33290             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
33291         }
33292         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
33293             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
33294                 bottomRightBasic[0] :
33295                 bottomLeftBasic[0];
33296             var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
33297             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
33298         }
33299         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
33300             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
33301                 bottomLeftBasic[1] :
33302                 topLeftBasic[1];
33303             var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
33304             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
33305         }
33306         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
33307     };
33308     /**
33309      * Determine if an event occured inside an element.
33310      *
33311      * @param {Event} event - Event containing clientX and clientY properties.
33312      * @param {HTMLElement} element - HTML element.
33313      * @returns {boolean} Value indicating if the event occured inside the element or not.
33314      */
33315     ViewportCoords.prototype.insideElement = function (event, element) {
33316         var clientRect = element.getBoundingClientRect();
33317         var minX = clientRect.left + element.clientLeft;
33318         var maxX = minX + element.clientWidth;
33319         var minY = clientRect.top + element.clientTop;
33320         var maxY = minY + element.clientHeight;
33321         return event.clientX > minX &&
33322             event.clientX < maxX &&
33323             event.clientY > minY &&
33324             event.clientY < maxY;
33325     };
33326     /**
33327      * Project 3D world coordinates to canvas coordinates.
33328      *
33329      * @param {Array<number>} point3D - 3D world coordinates.
33330      * @param {HTMLElement} container - The viewer container.
33331      * @param {THREE.Camera} camera - Camera used in rendering.
33332      * @returns {Array<number>} 2D canvas coordinates.
33333      */
33334     ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
33335         var viewport = this.projectToViewport(point3d, camera);
33336         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
33337         return canvas;
33338     };
33339     /**
33340      * Project 3D world coordinates to viewport coordinates.
33341      *
33342      * @param {Array<number>} point3D - 3D world coordinates.
33343      * @param {THREE.Camera} camera - Camera used in rendering.
33344      * @returns {Array<number>} 2D viewport coordinates.
33345      */
33346     ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
33347         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
33348             .project(camera);
33349         return [viewport.x, viewport.y];
33350     };
33351     /**
33352      * Uproject canvas coordinates to 3D world coordinates.
33353      *
33354      * @param {number} canvasX - Canvas X coordinate.
33355      * @param {number} canvasY - Canvas Y coordinate.
33356      * @param {HTMLElement} container - The viewer container.
33357      * @param {THREE.Camera} camera - Camera used in rendering.
33358      * @returns {Array<number>} 3D world coordinates.
33359      */
33360     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
33361         var viewport = this.canvasToViewport(canvasX, canvasY, container);
33362         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
33363         return point3d;
33364     };
33365     /**
33366      * Unproject viewport coordinates to 3D world coordinates.
33367      *
33368      * @param {number} viewportX - Viewport X coordinate.
33369      * @param {number} viewportY - Viewport Y coordinate.
33370      * @param {THREE.Camera} camera - Camera used in rendering.
33371      * @returns {Array<number>} 3D world coordinates.
33372      */
33373     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
33374         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
33375             .unproject(camera);
33376         return point3d;
33377     };
33378     /**
33379      * Convert viewport coordinates to basic coordinates.
33380      *
33381      * @description Transform origin and camera position needs to be the
33382      * equal for reliable return value.
33383      *
33384      * @param {number} viewportX - Viewport X coordinate.
33385      * @param {number} viewportY - Viewport Y coordinate.
33386      * @param {Transform} transform - Transform of the node to unproject from.
33387      * @param {THREE.Camera} camera - Camera used in rendering.
33388      * @returns {Array<number>} 2D basic coordinates.
33389      */
33390     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
33391         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
33392             .unproject(camera)
33393             .toArray();
33394         var basic = transform.projectBasic(point3d);
33395         return basic;
33396     };
33397     /**
33398      * Convert viewport coordinates to canvas coordinates.
33399      *
33400      * @param {number} viewportX - Viewport X coordinate.
33401      * @param {number} viewportY - Viewport Y coordinate.
33402      * @param {HTMLElement} container - The viewer container.
33403      * @returns {Array<number>} 2D canvas coordinates.
33404      */
33405     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
33406         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
33407         var canvasX = canvasWidth * (viewportX + 1) / 2;
33408         var canvasY = -canvasHeight * (viewportY - 1) / 2;
33409         return [canvasX, canvasY];
33410     };
33411     /**
33412      * Convert 3D world coordinates to 3D camera coordinates.
33413      *
33414      * @param {number} point3D - 3D point in world coordinate system.
33415      * @param {THREE.Camera} camera - Camera used in rendering.
33416      * @returns {Array<number>} 3D camera coordinates.
33417      */
33418     ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
33419         var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
33420             .applyMatrix4(camera.matrixWorldInverse);
33421         return pointCamera.toArray();
33422     };
33423     return ViewportCoords;
33424 }());
33425 exports.ViewportCoords = ViewportCoords;
33426 exports.default = ViewportCoords;
33427
33428 },{"three":180}],329:[function(require,module,exports){
33429 "use strict";
33430 Object.defineProperty(exports, "__esModule", { value: true });
33431 /**
33432  * @class Filter
33433  *
33434  * @classdesc Represents a class for creating node filters. Implementation and
33435  * definitions based on https://github.com/mapbox/feature-filter.
33436  */
33437 var FilterCreator = (function () {
33438     function FilterCreator() {
33439     }
33440     /**
33441      * Create a filter from a filter expression.
33442      *
33443      * @description The following filters are supported:
33444      *
33445      * Comparison
33446      * `==`
33447      * `!=`
33448      * `<`
33449      * `<=`
33450      * `>`
33451      * `>=`
33452      *
33453      * Set membership
33454      * `in`
33455      * `!in`
33456      *
33457      * Combining
33458      * `all`
33459      *
33460      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
33461      * expression.
33462      * @returns {FilterFunction} Function taking a node and returning a boolean that
33463      * indicates whether the node passed the test or not.
33464      */
33465     FilterCreator.prototype.createFilter = function (filter) {
33466         return new Function("node", "return " + this._compile(filter) + ";");
33467     };
33468     FilterCreator.prototype._compile = function (filter) {
33469         if (filter == null || filter.length <= 1) {
33470             return "true";
33471         }
33472         var operator = filter[0];
33473         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
33474             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
33475                 operator === ">" ||
33476                     operator === ">=" ||
33477                     operator === "<" ||
33478                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
33479                     operator === "in" ?
33480                         this._compileInOp(filter[1], filter.slice(2)) :
33481                         operator === "!in" ?
33482                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
33483                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
33484                                 "true";
33485         return "(" + operation + ")";
33486     };
33487     FilterCreator.prototype._compare = function (a, b) {
33488         return a < b ? -1 : a > b ? 1 : 0;
33489     };
33490     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
33491         var left = this._compilePropertyReference(property);
33492         var right = JSON.stringify(value);
33493         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
33494     };
33495     FilterCreator.prototype._compileInOp = function (property, values) {
33496         var compare = this._compare;
33497         var left = JSON.stringify(values.sort(compare));
33498         var right = this._compilePropertyReference(property);
33499         return left + ".indexOf(" + right + ")!==-1";
33500     };
33501     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
33502         var compile = this._compile.bind(this);
33503         return filters.map(compile).join(operator);
33504     };
33505     FilterCreator.prototype._compileNegation = function (expression) {
33506         return "!(" + expression + ")";
33507     };
33508     FilterCreator.prototype._compilePropertyReference = function (property) {
33509         return "node[" + JSON.stringify(property) + "]";
33510     };
33511     return FilterCreator;
33512 }());
33513 exports.FilterCreator = FilterCreator;
33514 exports.default = FilterCreator;
33515
33516 },{}],330:[function(require,module,exports){
33517 "use strict";
33518 /// <reference path="../../typings/index.d.ts" />
33519 Object.defineProperty(exports, "__esModule", { value: true });
33520 var rbush = require("rbush");
33521 var Subject_1 = require("rxjs/Subject");
33522 require("rxjs/add/observable/from");
33523 require("rxjs/add/operator/catch");
33524 require("rxjs/add/operator/do");
33525 require("rxjs/add/operator/finally");
33526 require("rxjs/add/operator/map");
33527 require("rxjs/add/operator/publish");
33528 var Edge_1 = require("../Edge");
33529 var Error_1 = require("../Error");
33530 var Graph_1 = require("../Graph");
33531 /**
33532  * @class Graph
33533  *
33534  * @classdesc Represents a graph of nodes with edges.
33535  */
33536 var Graph = (function () {
33537     /**
33538      * Create a new graph instance.
33539      *
33540      * @param {APIv3} [apiV3] - API instance for retrieving data.
33541      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
33542      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
33543      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
33544      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
33545      * @param {IGraphConfiguration} [configuration] - Configuration struct.
33546      */
33547     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
33548         this._apiV3 = apiV3;
33549         this._cachedNodes = {};
33550         this._cachedNodeTiles = {};
33551         this._cachedSpatialEdges = {};
33552         this._cachedTiles = {};
33553         this._cachingFill$ = {};
33554         this._cachingFull$ = {};
33555         this._cachingSequences$ = {};
33556         this._cachingSpatialArea$ = {};
33557         this._cachingTiles$ = {};
33558         this._changed$ = new Subject_1.Subject();
33559         this._defaultAlt = 2;
33560         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
33561         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
33562         this._filter = this._filterCreator.createFilter(undefined);
33563         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
33564         this._configuration = configuration != null ?
33565             configuration :
33566             {
33567                 maxSequences: 50,
33568                 maxUnusedNodes: 100,
33569                 maxUnusedTiles: 20,
33570             };
33571         this._nodes = {};
33572         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
33573         this._nodeIndexTiles = {};
33574         this._nodeToTile = {};
33575         this._preStored = {};
33576         this._requiredNodeTiles = {};
33577         this._requiredSpatialArea = {};
33578         this._sequences = {};
33579         this._tilePrecision = 7;
33580         this._tileThreshold = 20;
33581     }
33582     Object.defineProperty(Graph.prototype, "changed$", {
33583         /**
33584          * Get changed$.
33585          *
33586          * @returns {Observable<Graph>} Observable emitting
33587          * the graph every time it has changed.
33588          */
33589         get: function () {
33590             return this._changed$;
33591         },
33592         enumerable: true,
33593         configurable: true
33594     });
33595     /**
33596      * Retrieve and cache node fill properties.
33597      *
33598      * @param {string} key - Key of node to fill.
33599      * @returns {Observable<Graph>} Observable emitting the graph
33600      * when the node has been updated.
33601      * @throws {GraphMapillaryError} When the operation is not valid on the
33602      * current graph.
33603      */
33604     Graph.prototype.cacheFill$ = function (key) {
33605         var _this = this;
33606         if (key in this._cachingFull$) {
33607             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
33608         }
33609         if (!this.hasNode(key)) {
33610             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
33611         }
33612         if (key in this._cachingFill$) {
33613             return this._cachingFill$[key];
33614         }
33615         var node = this.getNode(key);
33616         if (node.full) {
33617             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
33618         }
33619         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
33620             .do(function (imageByKeyFill) {
33621             if (!node.full) {
33622                 _this._makeFull(node, imageByKeyFill[key]);
33623             }
33624             delete _this._cachingFill$[key];
33625         })
33626             .map(function (imageByKeyFill) {
33627             return _this;
33628         })
33629             .finally(function () {
33630             if (key in _this._cachingFill$) {
33631                 delete _this._cachingFill$[key];
33632             }
33633             _this._changed$.next(_this);
33634         })
33635             .publish()
33636             .refCount();
33637         return this._cachingFill$[key];
33638     };
33639     /**
33640      * Retrieve and cache full node properties.
33641      *
33642      * @param {string} key - Key of node to fill.
33643      * @returns {Observable<Graph>} Observable emitting the graph
33644      * when the node has been updated.
33645      * @throws {GraphMapillaryError} When the operation is not valid on the
33646      * current graph.
33647      */
33648     Graph.prototype.cacheFull$ = function (key) {
33649         var _this = this;
33650         if (key in this._cachingFull$) {
33651             return this._cachingFull$[key];
33652         }
33653         if (this.hasNode(key)) {
33654             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
33655         }
33656         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
33657             .do(function (imageByKeyFull) {
33658             var fn = imageByKeyFull[key];
33659             if (_this.hasNode(key)) {
33660                 var node = _this.getNode(key);
33661                 if (!node.full) {
33662                     _this._makeFull(node, fn);
33663                 }
33664             }
33665             else {
33666                 if (fn.sequence == null || fn.sequence.key == null) {
33667                     throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
33668                 }
33669                 var node = new Graph_1.Node(fn);
33670                 _this._makeFull(node, fn);
33671                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
33672                 _this._preStore(h, node);
33673                 _this._setNode(node);
33674                 delete _this._cachingFull$[key];
33675             }
33676         })
33677             .map(function (imageByKeyFull) {
33678             return _this;
33679         })
33680             .finally(function () {
33681             if (key in _this._cachingFull$) {
33682                 delete _this._cachingFull$[key];
33683             }
33684             _this._changed$.next(_this);
33685         })
33686             .publish()
33687             .refCount();
33688         return this._cachingFull$[key];
33689     };
33690     /**
33691      * Retrieve and cache a node sequence.
33692      *
33693      * @param {string} key - Key of node for which to retrieve sequence.
33694      * @returns {Observable<Graph>} Observable emitting the graph
33695      * when the sequence has been retrieved.
33696      * @throws {GraphMapillaryError} When the operation is not valid on the
33697      * current graph.
33698      */
33699     Graph.prototype.cacheNodeSequence$ = function (key) {
33700         if (!this.hasNode(key)) {
33701             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
33702         }
33703         var node = this.getNode(key);
33704         if (node.sequenceKey in this._sequences) {
33705             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
33706         }
33707         return this._cacheSequence$(node.sequenceKey);
33708     };
33709     /**
33710      * Retrieve and cache a sequence.
33711      *
33712      * @param {string} sequenceKey - Key of sequence to cache.
33713      * @returns {Observable<Graph>} Observable emitting the graph
33714      * when the sequence has been retrieved.
33715      * @throws {GraphMapillaryError} When the operation is not valid on the
33716      * current graph.
33717      */
33718     Graph.prototype.cacheSequence$ = function (sequenceKey) {
33719         if (sequenceKey in this._sequences) {
33720             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
33721         }
33722         return this._cacheSequence$(sequenceKey);
33723     };
33724     /**
33725      * Cache sequence edges for a node.
33726      *
33727      * @param {string} key - Key of node.
33728      * @throws {GraphMapillaryError} When the operation is not valid on the
33729      * current graph.
33730      */
33731     Graph.prototype.cacheSequenceEdges = function (key) {
33732         var node = this.getNode(key);
33733         if (!(node.sequenceKey in this._sequences)) {
33734             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
33735         }
33736         var sequence = this._sequences[node.sequenceKey].sequence;
33737         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
33738         node.cacheSequenceEdges(edges);
33739     };
33740     /**
33741      * Retrieve and cache full nodes for a node spatial area.
33742      *
33743      * @param {string} key - Key of node for which to retrieve sequence.
33744      * @returns {Observable<Graph>} Observable emitting the graph
33745      * when the nodes in the spatial area has been made full.
33746      * @throws {GraphMapillaryError} When the operation is not valid on the
33747      * current graph.
33748      */
33749     Graph.prototype.cacheSpatialArea$ = function (key) {
33750         var _this = this;
33751         if (!this.hasNode(key)) {
33752             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
33753         }
33754         if (key in this._cachedSpatialEdges) {
33755             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
33756         }
33757         if (!(key in this._requiredSpatialArea)) {
33758             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
33759         }
33760         var spatialArea = this._requiredSpatialArea[key];
33761         if (Object.keys(spatialArea.cacheNodes).length === 0) {
33762             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
33763         }
33764         if (key in this._cachingSpatialArea$) {
33765             return this._cachingSpatialArea$[key];
33766         }
33767         var batches = [];
33768         while (spatialArea.cacheKeys.length > 0) {
33769             batches.push(spatialArea.cacheKeys.splice(0, 200));
33770         }
33771         var batchesToCache = batches.length;
33772         var spatialNodes$ = [];
33773         var _loop_1 = function (batch) {
33774             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
33775                 .do(function (imageByKeyFill) {
33776                 for (var fillKey in imageByKeyFill) {
33777                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
33778                         continue;
33779                     }
33780                     var spatialNode = spatialArea.cacheNodes[fillKey];
33781                     if (spatialNode.full) {
33782                         delete spatialArea.cacheNodes[fillKey];
33783                         continue;
33784                     }
33785                     var fillNode = imageByKeyFill[fillKey];
33786                     _this._makeFull(spatialNode, fillNode);
33787                     delete spatialArea.cacheNodes[fillKey];
33788                 }
33789                 if (--batchesToCache === 0) {
33790                     delete _this._cachingSpatialArea$[key];
33791                 }
33792             })
33793                 .map(function (imageByKeyFill) {
33794                 return _this;
33795             })
33796                 .catch(function (error) {
33797                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
33798                     var batchKey = batch_1[_i];
33799                     if (batchKey in spatialArea.all) {
33800                         delete spatialArea.all[batchKey];
33801                     }
33802                     if (batchKey in spatialArea.cacheNodes) {
33803                         delete spatialArea.cacheNodes[batchKey];
33804                     }
33805                 }
33806                 if (--batchesToCache === 0) {
33807                     delete _this._cachingSpatialArea$[key];
33808                 }
33809                 throw error;
33810             })
33811                 .finally(function () {
33812                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
33813                     _this._changed$.next(_this);
33814                 }
33815             })
33816                 .publish()
33817                 .refCount();
33818             spatialNodes$.push(spatialNodeBatch$);
33819         };
33820         var this_1 = this;
33821         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
33822             var batch = batches_1[_i];
33823             _loop_1(batch);
33824         }
33825         this._cachingSpatialArea$[key] = spatialNodes$;
33826         return spatialNodes$;
33827     };
33828     /**
33829      * Cache spatial edges for a node.
33830      *
33831      * @param {string} key - Key of node.
33832      * @throws {GraphMapillaryError} When the operation is not valid on the
33833      * current graph.
33834      */
33835     Graph.prototype.cacheSpatialEdges = function (key) {
33836         if (key in this._cachedSpatialEdges) {
33837             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
33838         }
33839         var node = this.getNode(key);
33840         var sequence = this._sequences[node.sequenceKey].sequence;
33841         var fallbackKeys = [];
33842         var prevKey = sequence.findPrevKey(node.key);
33843         if (prevKey != null) {
33844             fallbackKeys.push(prevKey);
33845         }
33846         var nextKey = sequence.findNextKey(node.key);
33847         if (nextKey != null) {
33848             fallbackKeys.push(nextKey);
33849         }
33850         var allSpatialNodes = this._requiredSpatialArea[key].all;
33851         var potentialNodes = [];
33852         var filter = this._filter;
33853         for (var spatialNodeKey in allSpatialNodes) {
33854             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
33855                 continue;
33856             }
33857             var spatialNode = allSpatialNodes[spatialNodeKey];
33858             if (filter(spatialNode)) {
33859                 potentialNodes.push(spatialNode);
33860             }
33861         }
33862         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
33863         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
33864         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
33865         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
33866         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
33867         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
33868         node.cacheSpatialEdges(edges);
33869         this._cachedSpatialEdges[key] = node;
33870         delete this._requiredSpatialArea[key];
33871         delete this._cachedNodeTiles[key];
33872     };
33873     /**
33874      * Retrieve and cache geohash tiles for a node.
33875      *
33876      * @param {string} key - Key of node for which to retrieve tiles.
33877      * @returns {Observable<Graph>} Observable emitting the graph
33878      * when the tiles required for the node has been cached.
33879      * @throws {GraphMapillaryError} When the operation is not valid on the
33880      * current graph.
33881      */
33882     Graph.prototype.cacheTiles$ = function (key) {
33883         var _this = this;
33884         if (key in this._cachedNodeTiles) {
33885             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
33886         }
33887         if (key in this._cachedSpatialEdges) {
33888             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
33889         }
33890         if (!(key in this._requiredNodeTiles)) {
33891             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
33892         }
33893         var nodeTiles = this._requiredNodeTiles[key];
33894         if (nodeTiles.cache.length === 0 &&
33895             nodeTiles.caching.length === 0) {
33896             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
33897         }
33898         if (!this.hasNode(key)) {
33899             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
33900         }
33901         var hs = nodeTiles.cache.slice();
33902         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
33903         nodeTiles.cache = [];
33904         var cacheTiles$ = [];
33905         var _loop_2 = function (h) {
33906             var cacheTile$ = null;
33907             if (h in this_2._cachingTiles$) {
33908                 cacheTile$ = this_2._cachingTiles$[h];
33909             }
33910             else {
33911                 cacheTile$ = this_2._apiV3.imagesByH$([h])
33912                     .do(function (imagesByH) {
33913                     var coreNodes = imagesByH[h];
33914                     if (h in _this._cachedTiles) {
33915                         return;
33916                     }
33917                     _this._nodeIndexTiles[h] = [];
33918                     _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
33919                     var hCache = _this._cachedTiles[h].nodes;
33920                     var preStored = _this._removeFromPreStore(h);
33921                     for (var index in coreNodes) {
33922                         if (!coreNodes.hasOwnProperty(index)) {
33923                             continue;
33924                         }
33925                         var coreNode = coreNodes[index];
33926                         if (coreNode == null) {
33927                             break;
33928                         }
33929                         if (coreNode.sequence == null ||
33930                             coreNode.sequence.key == null) {
33931                             console.warn("Sequence missing, discarding (" + coreNode.key + ")");
33932                             continue;
33933                         }
33934                         if (preStored != null && coreNode.key in preStored) {
33935                             var node_1 = preStored[coreNode.key];
33936                             delete preStored[coreNode.key];
33937                             hCache.push(node_1);
33938                             var nodeIndexItem_1 = {
33939                                 lat: node_1.latLon.lat,
33940                                 lon: node_1.latLon.lon,
33941                                 node: node_1,
33942                             };
33943                             _this._nodeIndex.insert(nodeIndexItem_1);
33944                             _this._nodeIndexTiles[h].push(nodeIndexItem_1);
33945                             _this._nodeToTile[node_1.key] = h;
33946                             continue;
33947                         }
33948                         var node = new Graph_1.Node(coreNode);
33949                         hCache.push(node);
33950                         var nodeIndexItem = {
33951                             lat: node.latLon.lat,
33952                             lon: node.latLon.lon,
33953                             node: node,
33954                         };
33955                         _this._nodeIndex.insert(nodeIndexItem);
33956                         _this._nodeIndexTiles[h].push(nodeIndexItem);
33957                         _this._nodeToTile[node.key] = h;
33958                         _this._setNode(node);
33959                     }
33960                     delete _this._cachingTiles$[h];
33961                 })
33962                     .map(function (imagesByH) {
33963                     return _this;
33964                 })
33965                     .catch(function (error) {
33966                     delete _this._cachingTiles$[h];
33967                     throw error;
33968                 })
33969                     .publish()
33970                     .refCount();
33971                 this_2._cachingTiles$[h] = cacheTile$;
33972             }
33973             cacheTiles$.push(cacheTile$
33974                 .do(function (graph) {
33975                 var index = nodeTiles.caching.indexOf(h);
33976                 if (index > -1) {
33977                     nodeTiles.caching.splice(index, 1);
33978                 }
33979                 if (nodeTiles.caching.length === 0 &&
33980                     nodeTiles.cache.length === 0) {
33981                     delete _this._requiredNodeTiles[key];
33982                     _this._cachedNodeTiles[key] = true;
33983                 }
33984             })
33985                 .catch(function (error) {
33986                 var index = nodeTiles.caching.indexOf(h);
33987                 if (index > -1) {
33988                     nodeTiles.caching.splice(index, 1);
33989                 }
33990                 if (nodeTiles.caching.length === 0 &&
33991                     nodeTiles.cache.length === 0) {
33992                     delete _this._requiredNodeTiles[key];
33993                     _this._cachedNodeTiles[key] = true;
33994                 }
33995                 throw error;
33996             })
33997                 .finally(function () {
33998                 _this._changed$.next(_this);
33999             })
34000                 .publish()
34001                 .refCount());
34002         };
34003         var this_2 = this;
34004         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
34005             var h = _a[_i];
34006             _loop_2(h);
34007         }
34008         return cacheTiles$;
34009     };
34010     /**
34011      * Initialize the cache for a node.
34012      *
34013      * @param {string} key - Key of node.
34014      * @throws {GraphMapillaryError} When the operation is not valid on the
34015      * current graph.
34016      */
34017     Graph.prototype.initializeCache = function (key) {
34018         if (key in this._cachedNodes) {
34019             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
34020         }
34021         var node = this.getNode(key);
34022         node.initializeCache(new Graph_1.NodeCache());
34023         var accessed = new Date().getTime();
34024         this._cachedNodes[key] = { accessed: accessed, node: node };
34025         this._updateCachedTileAccess(key, accessed);
34026     };
34027     /**
34028      * Get a value indicating if the graph is fill caching a node.
34029      *
34030      * @param {string} key - Key of node.
34031      * @returns {boolean} Value indicating if the node is being fill cached.
34032      */
34033     Graph.prototype.isCachingFill = function (key) {
34034         return key in this._cachingFill$;
34035     };
34036     /**
34037      * Get a value indicating if the graph is fully caching a node.
34038      *
34039      * @param {string} key - Key of node.
34040      * @returns {boolean} Value indicating if the node is being fully cached.
34041      */
34042     Graph.prototype.isCachingFull = function (key) {
34043         return key in this._cachingFull$;
34044     };
34045     /**
34046      * Get a value indicating if the graph is caching a sequence of a node.
34047      *
34048      * @param {string} key - Key of node.
34049      * @returns {boolean} Value indicating if the sequence of a node is
34050      * being cached.
34051      */
34052     Graph.prototype.isCachingNodeSequence = function (key) {
34053         var node = this.getNode(key);
34054         return node.sequenceKey in this._cachingSequences$;
34055     };
34056     /**
34057      * Get a value indicating if the graph is caching a sequence.
34058      *
34059      * @param {string} sequenceKey - Key of sequence.
34060      * @returns {boolean} Value indicating if the sequence is
34061      * being cached.
34062      */
34063     Graph.prototype.isCachingSequence = function (sequenceKey) {
34064         return sequenceKey in this._cachingSequences$;
34065     };
34066     /**
34067      * Get a value indicating if the graph is caching the tiles
34068      * required for calculating spatial edges of a node.
34069      *
34070      * @param {string} key - Key of node.
34071      * @returns {boolean} Value indicating if the tiles of
34072      * a node are being cached.
34073      */
34074     Graph.prototype.isCachingTiles = function (key) {
34075         return key in this._requiredNodeTiles &&
34076             this._requiredNodeTiles[key].cache.length === 0 &&
34077             this._requiredNodeTiles[key].caching.length > 0;
34078     };
34079     /**
34080      * Get a value indicating if the cache has been initialized
34081      * for a node.
34082      *
34083      * @param {string} key - Key of node.
34084      * @returns {boolean} Value indicating if the cache has been
34085      * initialized for a node.
34086      */
34087     Graph.prototype.hasInitializedCache = function (key) {
34088         return key in this._cachedNodes;
34089     };
34090     /**
34091      * Get a value indicating if a node exist in the graph.
34092      *
34093      * @param {string} key - Key of node.
34094      * @returns {boolean} Value indicating if a node exist in the graph.
34095      */
34096     Graph.prototype.hasNode = function (key) {
34097         var accessed = new Date().getTime();
34098         this._updateCachedNodeAccess(key, accessed);
34099         this._updateCachedTileAccess(key, accessed);
34100         return key in this._nodes;
34101     };
34102     /**
34103      * Get a value indicating if a node sequence exist in the graph.
34104      *
34105      * @param {string} key - Key of node.
34106      * @returns {boolean} Value indicating if a node sequence exist
34107      * in the graph.
34108      */
34109     Graph.prototype.hasNodeSequence = function (key) {
34110         var node = this.getNode(key);
34111         var sequenceKey = node.sequenceKey;
34112         var hasNodeSequence = sequenceKey in this._sequences;
34113         if (hasNodeSequence) {
34114             this._sequences[sequenceKey].accessed = new Date().getTime();
34115         }
34116         return hasNodeSequence;
34117     };
34118     /**
34119      * Get a value indicating if a sequence exist in the graph.
34120      *
34121      * @param {string} sequenceKey - Key of sequence.
34122      * @returns {boolean} Value indicating if a sequence exist
34123      * in the graph.
34124      */
34125     Graph.prototype.hasSequence = function (sequenceKey) {
34126         var hasSequence = sequenceKey in this._sequences;
34127         if (hasSequence) {
34128             this._sequences[sequenceKey].accessed = new Date().getTime();
34129         }
34130         return hasSequence;
34131     };
34132     /**
34133      * Get a value indicating if the graph has fully cached
34134      * all nodes in the spatial area of a node.
34135      *
34136      * @param {string} key - Key of node.
34137      * @returns {boolean} Value indicating if the spatial area
34138      * of a node has been cached.
34139      */
34140     Graph.prototype.hasSpatialArea = function (key) {
34141         if (!this.hasNode(key)) {
34142             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
34143         }
34144         if (key in this._cachedSpatialEdges) {
34145             return true;
34146         }
34147         if (key in this._requiredSpatialArea) {
34148             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
34149         }
34150         var node = this.getNode(key);
34151         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
34152         var spatialItems = this._nodeIndex.search({
34153             maxX: bbox[1].lat,
34154             maxY: bbox[1].lon,
34155             minX: bbox[0].lat,
34156             minY: bbox[0].lon,
34157         });
34158         var spatialNodes = {
34159             all: {},
34160             cacheKeys: [],
34161             cacheNodes: {},
34162         };
34163         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
34164             var spatialItem = spatialItems_1[_i];
34165             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
34166             if (!spatialItem.node.full) {
34167                 spatialNodes.cacheKeys.push(spatialItem.node.key);
34168                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
34169             }
34170         }
34171         this._requiredSpatialArea[key] = spatialNodes;
34172         return spatialNodes.cacheKeys.length === 0;
34173     };
34174     /**
34175      * Get a value indicating if the graph has a tiles required
34176      * for a node.
34177      *
34178      * @param {string} key - Key of node.
34179      * @returns {boolean} Value indicating if the the tiles required
34180      * by a node has been cached.
34181      */
34182     Graph.prototype.hasTiles = function (key) {
34183         var _this = this;
34184         if (key in this._cachedNodeTiles) {
34185             return true;
34186         }
34187         if (key in this._cachedSpatialEdges) {
34188             return true;
34189         }
34190         if (!this.hasNode(key)) {
34191             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
34192         }
34193         var nodeTiles = { cache: [], caching: [] };
34194         if (!(key in this._requiredNodeTiles)) {
34195             var node = this.getNode(key);
34196             nodeTiles.cache = this._graphCalculator
34197                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
34198                 .filter(function (h) {
34199                 return !(h in _this._cachedTiles);
34200             });
34201             if (nodeTiles.cache.length > 0) {
34202                 this._requiredNodeTiles[key] = nodeTiles;
34203             }
34204         }
34205         else {
34206             nodeTiles = this._requiredNodeTiles[key];
34207         }
34208         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
34209     };
34210     /**
34211      * Get a node.
34212      *
34213      * @param {string} key - Key of node.
34214      * @returns {Node} Retrieved node.
34215      */
34216     Graph.prototype.getNode = function (key) {
34217         var accessed = new Date().getTime();
34218         this._updateCachedNodeAccess(key, accessed);
34219         this._updateCachedTileAccess(key, accessed);
34220         return this._nodes[key];
34221     };
34222     /**
34223      * Get a sequence.
34224      *
34225      * @param {string} sequenceKey - Key of sequence.
34226      * @returns {Node} Retrieved sequence.
34227      */
34228     Graph.prototype.getSequence = function (sequenceKey) {
34229         var sequenceAccess = this._sequences[sequenceKey];
34230         sequenceAccess.accessed = new Date().getTime();
34231         return sequenceAccess.sequence;
34232     };
34233     /**
34234      * Reset all spatial edges of the graph nodes.
34235      */
34236     Graph.prototype.resetSpatialEdges = function () {
34237         var cachedKeys = Object.keys(this._cachedSpatialEdges);
34238         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
34239             var cachedKey = cachedKeys_1[_i];
34240             var node = this._cachedSpatialEdges[cachedKey];
34241             node.resetSpatialEdges();
34242             delete this._cachedSpatialEdges[cachedKey];
34243         }
34244     };
34245     /**
34246      * Reset the complete graph but keep the nodes corresponding
34247      * to the supplied keys. All other nodes will be disposed.
34248      *
34249      * @param {Array<string>} keepKeys - Keys for nodes to keep
34250      * in graph after reset.
34251      */
34252     Graph.prototype.reset = function (keepKeys) {
34253         var nodes = [];
34254         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
34255             var key = keepKeys_1[_i];
34256             if (!this.hasNode(key)) {
34257                 throw new Error("Node does not exist " + key);
34258             }
34259             var node = this.getNode(key);
34260             node.resetSequenceEdges();
34261             node.resetSpatialEdges();
34262             nodes.push(node);
34263         }
34264         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
34265             var cachedKey = _b[_a];
34266             if (keepKeys.indexOf(cachedKey) !== -1) {
34267                 continue;
34268             }
34269             this._cachedNodes[cachedKey].node.dispose();
34270             delete this._cachedNodes[cachedKey];
34271         }
34272         this._cachedNodeTiles = {};
34273         this._cachedSpatialEdges = {};
34274         this._cachedTiles = {};
34275         this._cachingFill$ = {};
34276         this._cachingFull$ = {};
34277         this._cachingSequences$ = {};
34278         this._cachingSpatialArea$ = {};
34279         this._cachingTiles$ = {};
34280         this._nodes = {};
34281         this._nodeToTile = {};
34282         this._preStored = {};
34283         for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
34284             var node = nodes_1[_c];
34285             this._nodes[node.key] = node;
34286             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
34287             this._preStore(h, node);
34288         }
34289         this._requiredNodeTiles = {};
34290         this._requiredSpatialArea = {};
34291         this._sequences = {};
34292         this._nodeIndexTiles = {};
34293         this._nodeIndex.clear();
34294     };
34295     /**
34296      * Set the spatial node filter.
34297      *
34298      * @param {FilterExpression} filter - Filter expression to be applied
34299      * when calculating spatial edges.
34300      */
34301     Graph.prototype.setFilter = function (filter) {
34302         this._filter = this._filterCreator.createFilter(filter);
34303     };
34304     /**
34305      * Uncache the graph according to the graph configuration.
34306      *
34307      * @description Uncaches unused tiles, unused nodes and
34308      * sequences according to the numbers specified in the
34309      * graph configuration. Sequences does not have a direct
34310      * reference to either tiles or nodes and may be uncached
34311      * even if they are related to the nodes that should be kept.
34312      *
34313      * @param {Array<string>} keepKeys - Keys of nodes to keep in
34314      * graph unrelated to last access. Tiles related to those keys
34315      * will also be kept in graph.
34316      */
34317     Graph.prototype.uncache = function (keepKeys) {
34318         var keysInUse = {};
34319         this._addNewKeys(keysInUse, this._cachingFull$);
34320         this._addNewKeys(keysInUse, this._cachingFill$);
34321         this._addNewKeys(keysInUse, this._cachingTiles$);
34322         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
34323         this._addNewKeys(keysInUse, this._requiredNodeTiles);
34324         this._addNewKeys(keysInUse, this._requiredSpatialArea);
34325         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
34326             var key = keepKeys_2[_i];
34327             if (key in keysInUse) {
34328                 continue;
34329             }
34330             keysInUse[key] = true;
34331         }
34332         var keepHs = {};
34333         for (var key in keysInUse) {
34334             if (!keysInUse.hasOwnProperty(key)) {
34335                 continue;
34336             }
34337             var node = this._nodes[key];
34338             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
34339             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
34340                 var nodeH = nodeHs_1[_a];
34341                 if (!(nodeH in keepHs)) {
34342                     keepHs[nodeH] = true;
34343                 }
34344             }
34345         }
34346         var potentialHs = [];
34347         for (var h in this._cachedTiles) {
34348             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
34349                 continue;
34350             }
34351             potentialHs.push([h, this._cachedTiles[h]]);
34352         }
34353         var uncacheHs = potentialHs
34354             .sort(function (h1, h2) {
34355             return h2[1].accessed - h1[1].accessed;
34356         })
34357             .slice(this._configuration.maxUnusedTiles)
34358             .map(function (h) {
34359             return h[0];
34360         });
34361         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
34362             var uncacheH = uncacheHs_1[_b];
34363             this._uncacheTile(uncacheH);
34364         }
34365         var potentialNodes = [];
34366         for (var key in this._cachedNodes) {
34367             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
34368                 continue;
34369             }
34370             potentialNodes.push(this._cachedNodes[key]);
34371         }
34372         var uncacheNodes = potentialNodes
34373             .sort(function (n1, n2) {
34374             return n2.accessed - n1.accessed;
34375         })
34376             .slice(this._configuration.maxUnusedNodes);
34377         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
34378             var nodeAccess = uncacheNodes_1[_c];
34379             nodeAccess.node.uncache();
34380             var key = nodeAccess.node.key;
34381             delete this._cachedNodes[key];
34382             if (key in this._cachedNodeTiles) {
34383                 delete this._cachedNodeTiles[key];
34384             }
34385             if (key in this._cachedSpatialEdges) {
34386                 delete this._cachedSpatialEdges[key];
34387             }
34388         }
34389         var potentialSequences = [];
34390         for (var sequenceKey in this._sequences) {
34391             if (!this._sequences.hasOwnProperty(sequenceKey) ||
34392                 sequenceKey in this._cachingSequences$) {
34393                 continue;
34394             }
34395             potentialSequences.push(this._sequences[sequenceKey]);
34396         }
34397         var uncacheSequences = potentialSequences
34398             .sort(function (s1, s2) {
34399             return s2.accessed - s1.accessed;
34400         })
34401             .slice(this._configuration.maxSequences);
34402         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
34403             var sequenceAccess = uncacheSequences_1[_d];
34404             var sequenceKey = sequenceAccess.sequence.key;
34405             delete this._sequences[sequenceKey];
34406             sequenceAccess.sequence.dispose();
34407         }
34408     };
34409     Graph.prototype._addNewKeys = function (keys, dict) {
34410         for (var key in dict) {
34411             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
34412                 continue;
34413             }
34414             if (!(key in keys)) {
34415                 keys[key] = true;
34416             }
34417         }
34418     };
34419     Graph.prototype._cacheSequence$ = function (sequenceKey) {
34420         var _this = this;
34421         if (sequenceKey in this._cachingSequences$) {
34422             return this._cachingSequences$[sequenceKey];
34423         }
34424         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
34425             .do(function (sequenceByKey) {
34426             if (!(sequenceKey in _this._sequences)) {
34427                 _this._sequences[sequenceKey] = {
34428                     accessed: new Date().getTime(),
34429                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
34430                 };
34431             }
34432             delete _this._cachingSequences$[sequenceKey];
34433         })
34434             .map(function (sequenceByKey) {
34435             return _this;
34436         })
34437             .finally(function () {
34438             if (sequenceKey in _this._cachingSequences$) {
34439                 delete _this._cachingSequences$[sequenceKey];
34440             }
34441             _this._changed$.next(_this);
34442         })
34443             .publish()
34444             .refCount();
34445         return this._cachingSequences$[sequenceKey];
34446     };
34447     Graph.prototype._makeFull = function (node, fillNode) {
34448         if (fillNode.calt == null) {
34449             fillNode.calt = this._defaultAlt;
34450         }
34451         if (fillNode.c_rotation == null) {
34452             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
34453         }
34454         node.makeFull(fillNode);
34455     };
34456     Graph.prototype._preStore = function (h, node) {
34457         if (!(h in this._preStored)) {
34458             this._preStored[h] = {};
34459         }
34460         this._preStored[h][node.key] = node;
34461     };
34462     Graph.prototype._removeFromPreStore = function (h) {
34463         var preStored = null;
34464         if (h in this._preStored) {
34465             preStored = this._preStored[h];
34466             delete this._preStored[h];
34467         }
34468         return preStored;
34469     };
34470     Graph.prototype._setNode = function (node) {
34471         var key = node.key;
34472         if (this.hasNode(key)) {
34473             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
34474         }
34475         this._nodes[key] = node;
34476     };
34477     Graph.prototype._uncacheTile = function (h) {
34478         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
34479             var node = _a[_i];
34480             var key = node.key;
34481             delete this._nodes[key];
34482             delete this._nodeToTile[key];
34483             if (key in this._cachedNodes) {
34484                 delete this._cachedNodes[key];
34485             }
34486             if (key in this._cachedNodeTiles) {
34487                 delete this._cachedNodeTiles[key];
34488             }
34489             if (key in this._cachedSpatialEdges) {
34490                 delete this._cachedSpatialEdges[key];
34491             }
34492             node.dispose();
34493         }
34494         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
34495             var nodeIndexItem = _c[_b];
34496             this._nodeIndex.remove(nodeIndexItem);
34497         }
34498         delete this._nodeIndexTiles[h];
34499         delete this._cachedTiles[h];
34500     };
34501     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
34502         if (key in this._nodeToTile) {
34503             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
34504         }
34505     };
34506     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
34507         if (key in this._cachedNodes) {
34508             this._cachedNodes[key].accessed = accessed;
34509         }
34510     };
34511     return Graph;
34512 }());
34513 exports.Graph = Graph;
34514 exports.default = Graph;
34515
34516 },{"../Edge":231,"../Error":232,"../Graph":234,"rbush":25,"rxjs/Subject":34,"rxjs/add/observable/from":41,"rxjs/add/operator/catch":52,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/map":65,"rxjs/add/operator/publish":71}],331:[function(require,module,exports){
34517 "use strict";
34518 /// <reference path="../../typings/index.d.ts" />
34519 Object.defineProperty(exports, "__esModule", { value: true });
34520 var geohash = require("latlon-geohash");
34521 var THREE = require("three");
34522 var Geo_1 = require("../Geo");
34523 var GeoHashDirections = (function () {
34524     function GeoHashDirections() {
34525     }
34526     GeoHashDirections.n = "n";
34527     GeoHashDirections.nw = "nw";
34528     GeoHashDirections.w = "w";
34529     GeoHashDirections.sw = "sw";
34530     GeoHashDirections.s = "s";
34531     GeoHashDirections.se = "se";
34532     GeoHashDirections.e = "e";
34533     GeoHashDirections.ne = "ne";
34534     return GeoHashDirections;
34535 }());
34536 /**
34537  * @class GraphCalculator
34538  *
34539  * @classdesc Represents a calculator for graph entities.
34540  */
34541 var GraphCalculator = (function () {
34542     /**
34543      * Create a new graph calculator instance.
34544      *
34545      * @param {GeoCoords} geoCoords - Geo coords instance.
34546      */
34547     function GraphCalculator(geoCoords) {
34548         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
34549     }
34550     /**
34551      * Encode the geohash tile for geodetic coordinates.
34552      *
34553      * @param {ILatLon} latlon - Latitude and longitude to encode.
34554      * @param {number} precision - Precision of the encoding.
34555      *
34556      * @returns {string} The geohash tile for the lat, lon and precision.
34557      */
34558     GraphCalculator.prototype.encodeH = function (latLon, precision) {
34559         if (precision === void 0) { precision = 7; }
34560         return geohash.encode(latLon.lat, latLon.lon, precision);
34561     };
34562     /**
34563      * Encode the geohash tiles within a threshold from a position
34564      * using Manhattan distance.
34565      *
34566      * @param {ILatLon} latlon - Latitude and longitude to encode.
34567      * @param {number} precision - Precision of the encoding.
34568      * @param {number} threshold - Threshold of the encoding in meters.
34569      *
34570      * @returns {string} The geohash tiles reachable within the threshold.
34571      */
34572     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
34573         if (precision === void 0) { precision = 7; }
34574         if (threshold === void 0) { threshold = 20; }
34575         var h = geohash.encode(latLon.lat, latLon.lon, precision);
34576         var bounds = geohash.bounds(h);
34577         var ne = bounds.ne;
34578         var sw = bounds.sw;
34579         var neighbours = geohash.neighbours(h);
34580         var bl = [0, 0, 0];
34581         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
34582         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
34583         var left = position[0] - bl[0];
34584         var right = tr[0] - position[0];
34585         var bottom = position[1] - bl[1];
34586         var top = tr[1] - position[1];
34587         var l = left < threshold;
34588         var r = right < threshold;
34589         var b = bottom < threshold;
34590         var t = top < threshold;
34591         var hs = [h];
34592         if (t) {
34593             hs.push(neighbours[GeoHashDirections.n]);
34594         }
34595         if (t && l) {
34596             hs.push(neighbours[GeoHashDirections.nw]);
34597         }
34598         if (l) {
34599             hs.push(neighbours[GeoHashDirections.w]);
34600         }
34601         if (l && b) {
34602             hs.push(neighbours[GeoHashDirections.sw]);
34603         }
34604         if (b) {
34605             hs.push(neighbours[GeoHashDirections.s]);
34606         }
34607         if (b && r) {
34608             hs.push(neighbours[GeoHashDirections.se]);
34609         }
34610         if (r) {
34611             hs.push(neighbours[GeoHashDirections.e]);
34612         }
34613         if (r && t) {
34614             hs.push(neighbours[GeoHashDirections.ne]);
34615         }
34616         return hs;
34617     };
34618     /**
34619      * Get the bounding box corners for a circle with radius of a threshold
34620      * with center in a geodetic position.
34621      *
34622      * @param {ILatLon} latlon - Latitude and longitude to encode.
34623      * @param {number} threshold - Threshold distance from the position in meters.
34624      *
34625      * @returns {Array<ILatLon>} The south west and north east corners of the
34626      * bounding box.
34627      */
34628     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
34629         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
34630         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
34631         return [
34632             { lat: bl[0], lon: bl[1] },
34633             { lat: tr[0], lon: tr[1] },
34634         ];
34635     };
34636     /**
34637      * Convert a compass angle to an angle axis rotation vector.
34638      *
34639      * @param {number} compassAngle - The compass angle in degrees.
34640      * @param {number} orientation - The orientation of the original image.
34641      *
34642      * @returns {Array<number>} Angle axis rotation vector.
34643      */
34644     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
34645         var x = 0;
34646         var y = 0;
34647         var z = 0;
34648         switch (orientation) {
34649             case 1:
34650                 x = Math.PI / 2;
34651                 break;
34652             case 3:
34653                 x = -Math.PI / 2;
34654                 z = Math.PI;
34655                 break;
34656             case 6:
34657                 y = -Math.PI / 2;
34658                 z = -Math.PI / 2;
34659                 break;
34660             case 8:
34661                 y = Math.PI / 2;
34662                 z = Math.PI / 2;
34663                 break;
34664             default:
34665                 break;
34666         }
34667         var rz = new THREE.Matrix4().makeRotationZ(z);
34668         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
34669         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
34670         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
34671         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
34672     };
34673     return GraphCalculator;
34674 }());
34675 exports.GraphCalculator = GraphCalculator;
34676 exports.default = GraphCalculator;
34677
34678 },{"../Geo":233,"latlon-geohash":21,"three":180}],332:[function(require,module,exports){
34679 "use strict";
34680 Object.defineProperty(exports, "__esModule", { value: true });
34681 var Observable_1 = require("rxjs/Observable");
34682 var Subject_1 = require("rxjs/Subject");
34683 require("rxjs/add/operator/catch");
34684 require("rxjs/add/operator/concat");
34685 require("rxjs/add/operator/do");
34686 require("rxjs/add/operator/expand");
34687 require("rxjs/add/operator/finally");
34688 require("rxjs/add/operator/first");
34689 require("rxjs/add/operator/last");
34690 require("rxjs/add/operator/map");
34691 require("rxjs/add/operator/mergeMap");
34692 require("rxjs/add/operator/publishReplay");
34693 /**
34694  * @class GraphService
34695  *
34696  * @classdesc Represents a service for graph operations.
34697  */
34698 var GraphService = (function () {
34699     /**
34700      * Create a new graph service instance.
34701      *
34702      * @param {Graph} graph - Graph instance to be operated on.
34703      */
34704     function GraphService(graph, imageLoadingService) {
34705         this._graph$ = Observable_1.Observable
34706             .of(graph)
34707             .concat(graph.changed$)
34708             .publishReplay(1)
34709             .refCount();
34710         this._graph$.subscribe(function () { });
34711         this._imageLoadingService = imageLoadingService;
34712         this._firstGraphSubjects$ = [];
34713         this._initializeCacheSubscriptions = [];
34714         this._sequenceSubscriptions = [];
34715         this._spatialSubscriptions = [];
34716     }
34717     /**
34718      * Cache a node in the graph and retrieve it.
34719      *
34720      * @description When called, the full properties of
34721      * the node are retrieved and the node cache is initialized.
34722      * After that the node assets are cached and the node
34723      * is emitted to the observable when.
34724      * In parallel to caching the node assets, the sequence and
34725      * spatial edges of the node are cached. For this, the sequence
34726      * of the node and the required tiles and spatial nodes are
34727      * retrieved. The sequence and spatial edges may be set before
34728      * or after the node is returned.
34729      *
34730      * @param {string} key - Key of the node to cache.
34731      * @return {Observable<Node>} Observable emitting a single item,
34732      * the node, when it has been retrieved and its assets are cached.
34733      * @throws {Error} Propagates any IO node caching errors to the caller.
34734      */
34735     GraphService.prototype.cacheNode$ = function (key) {
34736         var _this = this;
34737         var firstGraphSubject$ = new Subject_1.Subject();
34738         this._firstGraphSubjects$.push(firstGraphSubject$);
34739         var firstGraph$ = firstGraphSubject$
34740             .publishReplay(1)
34741             .refCount();
34742         var node$ = firstGraph$
34743             .map(function (graph) {
34744             return graph.getNode(key);
34745         })
34746             .mergeMap(function (node) {
34747             return node.assetsCached ?
34748                 Observable_1.Observable.of(node) :
34749                 node.cacheAssets$();
34750         })
34751             .publishReplay(1)
34752             .refCount();
34753         node$.subscribe(function (node) {
34754             _this._imageLoadingService.loadnode$.next(node);
34755         }, function (error) {
34756             console.error("Failed to cache node (" + key + ")", error);
34757         });
34758         var initializeCacheSubscription = this._graph$
34759             .first()
34760             .mergeMap(function (graph) {
34761             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
34762                 return graph.cacheFull$(key);
34763             }
34764             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
34765                 return graph.cacheFill$(key);
34766             }
34767             return Observable_1.Observable.of(graph);
34768         })
34769             .do(function (graph) {
34770             if (!graph.hasInitializedCache(key)) {
34771                 graph.initializeCache(key);
34772             }
34773         })
34774             .finally(function () {
34775             if (initializeCacheSubscription == null) {
34776                 return;
34777             }
34778             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
34779             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
34780         })
34781             .subscribe(function (graph) {
34782             firstGraphSubject$.next(graph);
34783             firstGraphSubject$.complete();
34784         }, function (error) {
34785             firstGraphSubject$.error(error);
34786         });
34787         if (!initializeCacheSubscription.closed) {
34788             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
34789         }
34790         var sequenceSubscription = firstGraph$
34791             .mergeMap(function (graph) {
34792             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
34793                 return graph.cacheNodeSequence$(key);
34794             }
34795             return Observable_1.Observable.of(graph);
34796         })
34797             .do(function (graph) {
34798             if (!graph.getNode(key).sequenceEdges.cached) {
34799                 graph.cacheSequenceEdges(key);
34800             }
34801         })
34802             .finally(function () {
34803             if (sequenceSubscription == null) {
34804                 return;
34805             }
34806             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
34807         })
34808             .subscribe(function (graph) { return; }, function (error) {
34809             console.error("Failed to cache sequence edges (" + key + ").", error);
34810         });
34811         if (!sequenceSubscription.closed) {
34812             this._sequenceSubscriptions.push(sequenceSubscription);
34813         }
34814         var spatialSubscription = firstGraph$
34815             .expand(function (graph) {
34816             if (graph.hasTiles(key)) {
34817                 return Observable_1.Observable.empty();
34818             }
34819             return Observable_1.Observable
34820                 .from(graph.cacheTiles$(key))
34821                 .mergeMap(function (graph$) {
34822                 return graph$
34823                     .mergeMap(function (g) {
34824                     if (g.isCachingTiles(key)) {
34825                         return Observable_1.Observable.empty();
34826                     }
34827                     return Observable_1.Observable.of(g);
34828                 })
34829                     .catch(function (error, caught$) {
34830                     console.error("Failed to cache tile data (" + key + ").", error);
34831                     return Observable_1.Observable.empty();
34832                 });
34833             });
34834         })
34835             .last()
34836             .mergeMap(function (graph) {
34837             if (graph.hasSpatialArea(key)) {
34838                 return Observable_1.Observable.of(graph);
34839             }
34840             return Observable_1.Observable
34841                 .from(graph.cacheSpatialArea$(key))
34842                 .mergeMap(function (graph$) {
34843                 return graph$
34844                     .catch(function (error, caught$) {
34845                     console.error("Failed to cache spatial nodes (" + key + ").", error);
34846                     return Observable_1.Observable.empty();
34847                 });
34848             });
34849         })
34850             .last()
34851             .mergeMap(function (graph) {
34852             return graph.hasNodeSequence(key) ?
34853                 Observable_1.Observable.of(graph) :
34854                 graph.cacheNodeSequence$(key);
34855         })
34856             .do(function (graph) {
34857             if (!graph.getNode(key).spatialEdges.cached) {
34858                 graph.cacheSpatialEdges(key);
34859             }
34860         })
34861             .finally(function () {
34862             if (spatialSubscription == null) {
34863                 return;
34864             }
34865             _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
34866         })
34867             .subscribe(function (graph) { return; }, function (error) {
34868             console.error("Failed to cache spatial edges (" + key + ").", error);
34869         });
34870         if (!spatialSubscription.closed) {
34871             this._spatialSubscriptions.push(spatialSubscription);
34872         }
34873         return node$
34874             .first(function (node) {
34875             return node.assetsCached;
34876         });
34877     };
34878     /**
34879      * Cache a sequence in the graph and retrieve it.
34880      *
34881      * @param {string} sequenceKey - Sequence key.
34882      * @returns {Observable<Sequence>} Observable emitting a single item,
34883      * the sequence, when it has been retrieved and its assets are cached.
34884      * @throws {Error} Propagates any IO node caching errors to the caller.
34885      */
34886     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
34887         return this._graph$
34888             .first()
34889             .mergeMap(function (graph) {
34890             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
34891                 return graph.cacheSequence$(sequenceKey);
34892             }
34893             return Observable_1.Observable.of(graph);
34894         })
34895             .map(function (graph) {
34896             return graph.getSequence(sequenceKey);
34897         });
34898     };
34899     /**
34900      * Set a spatial edge filter on the graph.
34901      *
34902      * @description Resets the spatial edges of all cached nodes.
34903      *
34904      * @param {FilterExpression} filter - Filter expression to be applied.
34905      * @return {Observable<Graph>} Observable emitting a single item,
34906      * the graph, when the spatial edges have been reset.
34907      */
34908     GraphService.prototype.setFilter$ = function (filter) {
34909         this._resetSubscriptions(this._spatialSubscriptions);
34910         return this._graph$
34911             .first()
34912             .do(function (graph) {
34913             graph.resetSpatialEdges();
34914             graph.setFilter(filter);
34915         });
34916     };
34917     /**
34918      * Reset the graph.
34919      *
34920      * @description Resets the graph but keeps the nodes of the
34921      * supplied keys.
34922      *
34923      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
34924      * @return {Observable<Node>} Observable emitting a single item,
34925      * the graph, when it has been reset.
34926      */
34927     GraphService.prototype.reset$ = function (keepKeys) {
34928         this._abortSubjects(this._firstGraphSubjects$);
34929         this._resetSubscriptions(this._initializeCacheSubscriptions);
34930         this._resetSubscriptions(this._sequenceSubscriptions);
34931         this._resetSubscriptions(this._spatialSubscriptions);
34932         return this._graph$
34933             .first()
34934             .do(function (graph) {
34935             graph.reset(keepKeys);
34936         });
34937     };
34938     /**
34939      * Uncache the graph.
34940      *
34941      * @description Uncaches the graph by removing tiles, nodes and
34942      * sequences. Keeps the nodes of the supplied keys and the tiles
34943      * related to those nodes.
34944      *
34945      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
34946      * @return {Observable<Graph>} Observable emitting a single item,
34947      * the graph, when the graph has been uncached.
34948      */
34949     GraphService.prototype.uncache$ = function (keepKeys) {
34950         return this._graph$
34951             .first()
34952             .do(function (graph) {
34953             graph.uncache(keepKeys);
34954         });
34955     };
34956     GraphService.prototype._abortSubjects = function (subjects) {
34957         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
34958             var subject = _a[_i];
34959             this._removeFromArray(subject, subjects);
34960             subject.error(new Error("Cache node request was aborted."));
34961         }
34962     };
34963     GraphService.prototype._removeFromArray = function (object, objects) {
34964         var index = objects.indexOf(object);
34965         if (index !== -1) {
34966             objects.splice(index, 1);
34967         }
34968     };
34969     GraphService.prototype._resetSubscriptions = function (subscriptions) {
34970         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
34971             var subscription = _a[_i];
34972             this._removeFromArray(subscription, subscriptions);
34973             if (!subscription.closed) {
34974                 subscription.unsubscribe();
34975             }
34976         }
34977     };
34978     return GraphService;
34979 }());
34980 exports.GraphService = GraphService;
34981 exports.default = GraphService;
34982
34983 },{"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/concat":54,"rxjs/add/operator/do":59,"rxjs/add/operator/expand":60,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/last":64,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72}],333:[function(require,module,exports){
34984 "use strict";
34985 /// <reference path="../../typings/index.d.ts" />
34986 Object.defineProperty(exports, "__esModule", { value: true });
34987 var Subject_1 = require("rxjs/Subject");
34988 var ImageLoadingService = (function () {
34989     function ImageLoadingService() {
34990         this._loadnode$ = new Subject_1.Subject();
34991         this._loadstatus$ = this._loadnode$
34992             .scan(function (nodes, node) {
34993             nodes[node.key] = node.loadStatus;
34994             return nodes;
34995         }, {})
34996             .publishReplay(1)
34997             .refCount();
34998         this._loadstatus$.subscribe(function () { });
34999     }
35000     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
35001         get: function () {
35002             return this._loadnode$;
35003         },
35004         enumerable: true,
35005         configurable: true
35006     });
35007     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
35008         get: function () {
35009             return this._loadstatus$;
35010         },
35011         enumerable: true,
35012         configurable: true
35013     });
35014     return ImageLoadingService;
35015 }());
35016 exports.ImageLoadingService = ImageLoadingService;
35017
35018 },{"rxjs/Subject":34}],334:[function(require,module,exports){
35019 "use strict";
35020 /// <reference path="../../typings/index.d.ts" />
35021 Object.defineProperty(exports, "__esModule", { value: true });
35022 var Pbf = require("pbf");
35023 var MeshReader = (function () {
35024     function MeshReader() {
35025     }
35026     MeshReader.read = function (buffer) {
35027         var pbf = new Pbf(buffer);
35028         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
35029     };
35030     MeshReader._readMeshField = function (tag, mesh, pbf) {
35031         if (tag === 1) {
35032             mesh.vertices.push(pbf.readFloat());
35033         }
35034         else if (tag === 2) {
35035             mesh.faces.push(pbf.readVarint());
35036         }
35037     };
35038     return MeshReader;
35039 }());
35040 exports.MeshReader = MeshReader;
35041
35042 },{"pbf":23}],335:[function(require,module,exports){
35043 "use strict";
35044 Object.defineProperty(exports, "__esModule", { value: true });
35045 require("rxjs/add/observable/combineLatest");
35046 require("rxjs/add/operator/map");
35047 /**
35048  * @class Node
35049  *
35050  * @classdesc Represents a node in the navigation graph.
35051  *
35052  * Explanation of position and bearing properties:
35053  *
35054  * When images are uploaded they will have GPS information in the EXIF, this is what
35055  * is called `originalLatLon`(@link Node#originalLatLon).
35056  *
35057  * When Structure from Motions has been run for a node a `computedLatLon` that
35058  * differs from the `originalLatLon` will be created. It is different because
35059  * GPS positions are not very exact and SfM aligns the camera positions according
35060  * to the 3D reconstruction (@link Node#computedLatLon).
35061  *
35062  * At last there exist a `latLon` property which evaluates to
35063  * the `computedLatLon` from SfM if it exists but falls back
35064  * to the `originalLatLon` from the EXIF GPS otherwise (@link Node#latlon).
35065  *
35066  * Everything that is done in in the Viewer is based on the SfM positions,
35067  * i.e. `computedLatLon`. That is why the smooth transitions go in the right
35068  * direction (nd not in strange directions because of bad GPS).
35069  *
35070  * E.g. when placing a marker in the Viewer it is relative to the SfM
35071  * position i.e. the `computedLatLon`.
35072  *
35073  * The same concept as above also applies to the compass angle (or bearing) properties
35074  * `originalCa`, `computedCa` and `ca`.
35075  */
35076 var Node = (function () {
35077     /**
35078      * Create a new node instance.
35079      *
35080      * @description Nodes are always created internally by the library.
35081      * Nodes can not be added to the library through any API method.
35082      *
35083      * @param {ICoreNode} coreNode - Raw core node data.
35084      */
35085     function Node(core) {
35086         this._cache = null;
35087         this._core = core;
35088         this._fill = null;
35089     }
35090     Object.defineProperty(Node.prototype, "assetsCached", {
35091         /**
35092          * Get assets cached.
35093          *
35094          * @description The assets that need to be cached for this property
35095          * to report true are the following: fill properties, image and mesh.
35096          * The library ensures that the current node will always have the
35097          * assets cached.
35098          *
35099          * @returns {boolean} Value indicating whether all assets have been
35100          * cached.
35101          */
35102         get: function () {
35103             return this._core != null &&
35104                 this._fill != null &&
35105                 this._cache != null &&
35106                 this._cache.image != null &&
35107                 this._cache.mesh != null;
35108         },
35109         enumerable: true,
35110         configurable: true
35111     });
35112     Object.defineProperty(Node.prototype, "alt", {
35113         /**
35114          * Get alt.
35115          *
35116          * @description If SfM has not been run the computed altitude is
35117          * set to a default value of two meters.
35118          *
35119          * @returns {number} Altitude, in meters.
35120          */
35121         get: function () {
35122             return this._fill.calt;
35123         },
35124         enumerable: true,
35125         configurable: true
35126     });
35127     Object.defineProperty(Node.prototype, "ca", {
35128         /**
35129          * Get ca.
35130          *
35131          * @description If the SfM computed compass angle exists it will
35132          * be returned, otherwise the original EXIF compass angle.
35133          *
35134          * @returns {number} Compass angle, measured in degrees.
35135          */
35136         get: function () {
35137             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
35138         },
35139         enumerable: true,
35140         configurable: true
35141     });
35142     Object.defineProperty(Node.prototype, "capturedAt", {
35143         /**
35144          * Get capturedAt.
35145          *
35146          * @returns {number} Timestamp when the image was captured.
35147          */
35148         get: function () {
35149             return this._fill.captured_at;
35150         },
35151         enumerable: true,
35152         configurable: true
35153     });
35154     Object.defineProperty(Node.prototype, "computedCA", {
35155         /**
35156          * Get computedCA.
35157          *
35158          * @description Will not be set if SfM has not been run.
35159          *
35160          * @returns {number} SfM computed compass angle, measured in degrees.
35161          */
35162         get: function () {
35163             return this._fill.cca;
35164         },
35165         enumerable: true,
35166         configurable: true
35167     });
35168     Object.defineProperty(Node.prototype, "computedLatLon", {
35169         /**
35170          * Get computedLatLon.
35171          *
35172          * @description Will not be set if SfM has not been run.
35173          *
35174          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
35175          * measured in degrees.
35176          */
35177         get: function () {
35178             return this._core.cl;
35179         },
35180         enumerable: true,
35181         configurable: true
35182     });
35183     Object.defineProperty(Node.prototype, "focal", {
35184         /**
35185          * Get focal.
35186          *
35187          * @description Will not be set if SfM has not been run.
35188          *
35189          * @returns {number} SfM computed focal length.
35190          */
35191         get: function () {
35192             return this._fill.cfocal;
35193         },
35194         enumerable: true,
35195         configurable: true
35196     });
35197     Object.defineProperty(Node.prototype, "full", {
35198         /**
35199          * Get full.
35200          *
35201          * @description The library ensures that the current node will
35202          * always be full.
35203          *
35204          * @returns {boolean} Value indicating whether the node has all
35205          * properties filled.
35206          */
35207         get: function () {
35208             return this._fill != null;
35209         },
35210         enumerable: true,
35211         configurable: true
35212     });
35213     Object.defineProperty(Node.prototype, "fullPano", {
35214         /**
35215          * Get fullPano.
35216          *
35217          * @returns {boolean} Value indicating whether the node is a complete
35218          * 360 panorama.
35219          */
35220         get: function () {
35221             return this._fill.gpano != null &&
35222                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
35223                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
35224                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
35225                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
35226         },
35227         enumerable: true,
35228         configurable: true
35229     });
35230     Object.defineProperty(Node.prototype, "gpano", {
35231         /**
35232          * Get gpano.
35233          *
35234          * @description Will not be set for non panoramic images.
35235          *
35236          * @returns {IGPano} Panorama information for panorama images.
35237          */
35238         get: function () {
35239             return this._fill.gpano;
35240         },
35241         enumerable: true,
35242         configurable: true
35243     });
35244     Object.defineProperty(Node.prototype, "height", {
35245         /**
35246          * Get height.
35247          *
35248          * @returns {number} Height of original image, not adjusted
35249          * for orientation.
35250          */
35251         get: function () {
35252             return this._fill.height;
35253         },
35254         enumerable: true,
35255         configurable: true
35256     });
35257     Object.defineProperty(Node.prototype, "image", {
35258         /**
35259          * Get image.
35260          *
35261          * @description The image will always be set on the current node.
35262          *
35263          * @returns {HTMLImageElement} Cached image element of the node.
35264          */
35265         get: function () {
35266             return this._cache.image;
35267         },
35268         enumerable: true,
35269         configurable: true
35270     });
35271     Object.defineProperty(Node.prototype, "key", {
35272         /**
35273          * Get key.
35274          *
35275          * @returns {string} Unique key of the node.
35276          */
35277         get: function () {
35278             return this._core.key;
35279         },
35280         enumerable: true,
35281         configurable: true
35282     });
35283     Object.defineProperty(Node.prototype, "latLon", {
35284         /**
35285          * Get latLon.
35286          *
35287          * @description If the SfM computed latitude longitude exist
35288          * it will be returned, otherwise the original EXIF latitude
35289          * longitude.
35290          *
35291          * @returns {ILatLon} Latitude longitude in WGS84 datum,
35292          * measured in degrees.
35293          */
35294         get: function () {
35295             return this._core.cl != null ? this._core.cl : this._core.l;
35296         },
35297         enumerable: true,
35298         configurable: true
35299     });
35300     Object.defineProperty(Node.prototype, "loadStatus", {
35301         /**
35302          * Get loadStatus.
35303          *
35304          * @returns {ILoadStatus} Value indicating the load status
35305          * of the mesh and image.
35306          */
35307         get: function () {
35308             return this._cache.loadStatus;
35309         },
35310         enumerable: true,
35311         configurable: true
35312     });
35313     Object.defineProperty(Node.prototype, "merged", {
35314         /**
35315          * Get merged.
35316          *
35317          * @returns {boolean} Value indicating whether SfM has been
35318          * run on the node and the node has been merged into a
35319          * connected component.
35320          */
35321         get: function () {
35322             return this._fill != null &&
35323                 this._fill.merge_version != null &&
35324                 this._fill.merge_version > 0;
35325         },
35326         enumerable: true,
35327         configurable: true
35328     });
35329     Object.defineProperty(Node.prototype, "mergeCC", {
35330         /**
35331          * Get mergeCC.
35332          *
35333          * @description Will not be set if SfM has not yet been run on
35334          * node.
35335          *
35336          * @returns {number} SfM connected component key to which
35337          * image belongs.
35338          */
35339         get: function () {
35340             return this._fill.merge_cc;
35341         },
35342         enumerable: true,
35343         configurable: true
35344     });
35345     Object.defineProperty(Node.prototype, "mergeVersion", {
35346         /**
35347          * Get mergeVersion.
35348          *
35349          * @returns {number} Version for which SfM was run and image was merged.
35350          */
35351         get: function () {
35352             return this._fill.merge_version;
35353         },
35354         enumerable: true,
35355         configurable: true
35356     });
35357     Object.defineProperty(Node.prototype, "mesh", {
35358         /**
35359          * Get mesh.
35360          *
35361          * @description The mesh will always be set on the current node.
35362          *
35363          * @returns {IMesh} SfM triangulated mesh of reconstructed
35364          * atomic 3D points.
35365          */
35366         get: function () {
35367             return this._cache.mesh;
35368         },
35369         enumerable: true,
35370         configurable: true
35371     });
35372     Object.defineProperty(Node.prototype, "orientation", {
35373         /**
35374          * Get orientation.
35375          *
35376          * @returns {number} EXIF orientation of original image.
35377          */
35378         get: function () {
35379             return this._fill.orientation;
35380         },
35381         enumerable: true,
35382         configurable: true
35383     });
35384     Object.defineProperty(Node.prototype, "originalCA", {
35385         /**
35386          * Get originalCA.
35387          *
35388          * @returns {number} Original EXIF compass angle, measured in
35389          * degrees.
35390          */
35391         get: function () {
35392             return this._fill.ca;
35393         },
35394         enumerable: true,
35395         configurable: true
35396     });
35397     Object.defineProperty(Node.prototype, "originalLatLon", {
35398         /**
35399          * Get originalLatLon.
35400          *
35401          * @returns {ILatLon} Original EXIF latitude longitude in
35402          * WGS84 datum, measured in degrees.
35403          */
35404         get: function () {
35405             return this._core.l;
35406         },
35407         enumerable: true,
35408         configurable: true
35409     });
35410     Object.defineProperty(Node.prototype, "pano", {
35411         /**
35412          * Get pano.
35413          *
35414          * @returns {boolean} Value indicating whether the node is a panorama.
35415          * It could be a cropped or full panorama.
35416          */
35417         get: function () {
35418             return this._fill.gpano != null &&
35419                 this._fill.gpano.FullPanoWidthPixels != null;
35420         },
35421         enumerable: true,
35422         configurable: true
35423     });
35424     Object.defineProperty(Node.prototype, "projectKey", {
35425         /**
35426          * Get projectKey.
35427          *
35428          * @returns {string} Unique key of the project to which
35429          * the node belongs.
35430          */
35431         get: function () {
35432             return this._fill.project != null ?
35433                 this._fill.project.key :
35434                 null;
35435         },
35436         enumerable: true,
35437         configurable: true
35438     });
35439     Object.defineProperty(Node.prototype, "rotation", {
35440         /**
35441          * Get rotation.
35442          *
35443          * @description Will not be set if SfM has not been run.
35444          *
35445          * @returns {Array<number>} Rotation vector in angle axis representation.
35446          */
35447         get: function () {
35448             return this._fill.c_rotation;
35449         },
35450         enumerable: true,
35451         configurable: true
35452     });
35453     Object.defineProperty(Node.prototype, "scale", {
35454         /**
35455          * Get scale.
35456          *
35457          * @description Will not be set if SfM has not been run.
35458          *
35459          * @returns {number} Scale of atomic reconstruction.
35460          */
35461         get: function () {
35462             return this._fill.atomic_scale;
35463         },
35464         enumerable: true,
35465         configurable: true
35466     });
35467     Object.defineProperty(Node.prototype, "sequenceKey", {
35468         /**
35469          * Get sequenceKey.
35470          *
35471          * @returns {string} Unique key of the sequence to which
35472          * the node belongs.
35473          */
35474         get: function () {
35475             return this._core.sequence.key;
35476         },
35477         enumerable: true,
35478         configurable: true
35479     });
35480     Object.defineProperty(Node.prototype, "sequenceEdges", {
35481         /**
35482          * Get sequenceEdges.
35483          *
35484          * @returns {IEdgeStatus} Value describing the status of the
35485          * sequence edges.
35486          */
35487         get: function () {
35488             return this._cache.sequenceEdges;
35489         },
35490         enumerable: true,
35491         configurable: true
35492     });
35493     Object.defineProperty(Node.prototype, "sequenceEdges$", {
35494         /**
35495          * Get sequenceEdges$.
35496          *
35497          * @returns {Observable<IEdgeStatus>} Observable emitting
35498          * values describing the status of the sequence edges.
35499          */
35500         get: function () {
35501             return this._cache.sequenceEdges$;
35502         },
35503         enumerable: true,
35504         configurable: true
35505     });
35506     Object.defineProperty(Node.prototype, "spatialEdges", {
35507         /**
35508          * Get spatialEdges.
35509          *
35510          * @returns {IEdgeStatus} Value describing the status of the
35511          * spatial edges.
35512          */
35513         get: function () {
35514             return this._cache.spatialEdges;
35515         },
35516         enumerable: true,
35517         configurable: true
35518     });
35519     Object.defineProperty(Node.prototype, "spatialEdges$", {
35520         /**
35521          * Get spatialEdges$.
35522          *
35523          * @returns {Observable<IEdgeStatus>} Observable emitting
35524          * values describing the status of the spatial edges.
35525          */
35526         get: function () {
35527             return this._cache.spatialEdges$;
35528         },
35529         enumerable: true,
35530         configurable: true
35531     });
35532     Object.defineProperty(Node.prototype, "userKey", {
35533         /**
35534          * Get userKey.
35535          *
35536          * @returns {string} Unique key of the user who uploaded
35537          * the image.
35538          */
35539         get: function () {
35540             return this._fill.user.key;
35541         },
35542         enumerable: true,
35543         configurable: true
35544     });
35545     Object.defineProperty(Node.prototype, "username", {
35546         /**
35547          * Get username.
35548          *
35549          * @returns {string} Username of the user who uploaded
35550          * the image.
35551          */
35552         get: function () {
35553             return this._fill.user.username;
35554         },
35555         enumerable: true,
35556         configurable: true
35557     });
35558     Object.defineProperty(Node.prototype, "width", {
35559         /**
35560          * Get width.
35561          *
35562          * @returns {number} Width of original image, not
35563          * adjusted for orientation.
35564          */
35565         get: function () {
35566             return this._fill.width;
35567         },
35568         enumerable: true,
35569         configurable: true
35570     });
35571     /**
35572      * Cache the image and mesh assets.
35573      *
35574      * @description The assets are always cached internally by the
35575      * library prior to setting a node as the current node.
35576      *
35577      * @returns {Observable<Node>} Observable emitting this node whenever the
35578      * load status has changed and when the mesh or image has been fully loaded.
35579      */
35580     Node.prototype.cacheAssets$ = function () {
35581         var _this = this;
35582         return this._cache.cacheAssets$(this.key, this.pano, this.merged)
35583             .map(function (cache) {
35584             return _this;
35585         });
35586     };
35587     Node.prototype.cacheImage$ = function (imageSize) {
35588         var _this = this;
35589         return this._cache.cacheImage$(this.key, imageSize)
35590             .map(function (cache) {
35591             return _this;
35592         });
35593     };
35594     /**
35595      * Cache the sequence edges.
35596      *
35597      * @description The sequence edges are cached asynchronously
35598      * internally by the library.
35599      *
35600      * @param {Array<IEdge>} edges - Sequence edges to cache.
35601      */
35602     Node.prototype.cacheSequenceEdges = function (edges) {
35603         this._cache.cacheSequenceEdges(edges);
35604     };
35605     /**
35606      * Cache the spatial edges.
35607      *
35608      * @description The spatial edges are cached asynchronously
35609      * internally by the library.
35610      *
35611      * @param {Array<IEdge>} edges - Spatial edges to cache.
35612      */
35613     Node.prototype.cacheSpatialEdges = function (edges) {
35614         this._cache.cacheSpatialEdges(edges);
35615     };
35616     /**
35617      * Dispose the node.
35618      *
35619      * @description Disposes all cached assets.
35620      */
35621     Node.prototype.dispose = function () {
35622         if (this._cache != null) {
35623             this._cache.dispose();
35624             this._cache = null;
35625         }
35626         this._core = null;
35627         this._fill = null;
35628     };
35629     /**
35630      * Initialize the node cache.
35631      *
35632      * @description The node cache is initialized internally by
35633      * the library.
35634      *
35635      * @param {NodeCache} cache - The node cache to set as cache.
35636      */
35637     Node.prototype.initializeCache = function (cache) {
35638         if (this._cache != null) {
35639             throw new Error("Node cache already initialized (" + this.key + ").");
35640         }
35641         this._cache = cache;
35642     };
35643     /**
35644      * Fill the node with all properties.
35645      *
35646      * @description The node is filled internally by
35647      * the library.
35648      *
35649      * @param {IFillNode} fill - The fill node struct.
35650      */
35651     Node.prototype.makeFull = function (fill) {
35652         if (fill == null) {
35653             throw new Error("Fill can not be null.");
35654         }
35655         this._fill = fill;
35656     };
35657     /**
35658      * Reset the sequence edges.
35659      */
35660     Node.prototype.resetSequenceEdges = function () {
35661         this._cache.resetSequenceEdges();
35662     };
35663     /**
35664      * Reset the spatial edges.
35665      */
35666     Node.prototype.resetSpatialEdges = function () {
35667         this._cache.resetSpatialEdges();
35668     };
35669     /**
35670      * Clears the image and mesh assets, aborts
35671      * any outstanding requests and resets edges.
35672      */
35673     Node.prototype.uncache = function () {
35674         if (this._cache == null) {
35675             return;
35676         }
35677         this._cache.dispose();
35678         this._cache = null;
35679     };
35680     return Node;
35681 }());
35682 exports.Node = Node;
35683 exports.default = Node;
35684
35685 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":65}],336:[function(require,module,exports){
35686 (function (Buffer){
35687 "use strict";
35688 Object.defineProperty(exports, "__esModule", { value: true });
35689 var Subject_1 = require("rxjs/Subject");
35690 var Observable_1 = require("rxjs/Observable");
35691 require("rxjs/add/observable/combineLatest");
35692 require("rxjs/add/operator/publishReplay");
35693 var Graph_1 = require("../Graph");
35694 var Utils_1 = require("../Utils");
35695 /**
35696  * @class NodeCache
35697  *
35698  * @classdesc Represents the cached properties of a node.
35699  */
35700 var NodeCache = (function () {
35701     /**
35702      * Create a new node cache instance.
35703      */
35704     function NodeCache() {
35705         this._disposed = false;
35706         this._image = null;
35707         this._loadStatus = { loaded: 0, total: 0 };
35708         this._mesh = null;
35709         this._sequenceEdges = { cached: false, edges: [] };
35710         this._spatialEdges = { cached: false, edges: [] };
35711         this._sequenceEdgesChanged$ = new Subject_1.Subject();
35712         this._sequenceEdges$ = this._sequenceEdgesChanged$
35713             .startWith(this._sequenceEdges)
35714             .publishReplay(1)
35715             .refCount();
35716         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
35717         this._spatialEdgesChanged$ = new Subject_1.Subject();
35718         this._spatialEdges$ = this._spatialEdgesChanged$
35719             .startWith(this._spatialEdges)
35720             .publishReplay(1)
35721             .refCount();
35722         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
35723         this._cachingAssets$ = null;
35724     }
35725     Object.defineProperty(NodeCache.prototype, "image", {
35726         /**
35727          * Get image.
35728          *
35729          * @description Will not be set when assets have not been cached
35730          * or when the object has been disposed.
35731          *
35732          * @returns {HTMLImageElement} Cached image element of the node.
35733          */
35734         get: function () {
35735             return this._image;
35736         },
35737         enumerable: true,
35738         configurable: true
35739     });
35740     Object.defineProperty(NodeCache.prototype, "loadStatus", {
35741         /**
35742          * Get loadStatus.
35743          *
35744          * @returns {ILoadStatus} Value indicating the load status
35745          * of the mesh and image.
35746          */
35747         get: function () {
35748             return this._loadStatus;
35749         },
35750         enumerable: true,
35751         configurable: true
35752     });
35753     Object.defineProperty(NodeCache.prototype, "mesh", {
35754         /**
35755          * Get mesh.
35756          *
35757          * @description Will not be set when assets have not been cached
35758          * or when the object has been disposed.
35759          *
35760          * @returns {IMesh} SfM triangulated mesh of reconstructed
35761          * atomic 3D points.
35762          */
35763         get: function () {
35764             return this._mesh;
35765         },
35766         enumerable: true,
35767         configurable: true
35768     });
35769     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
35770         /**
35771          * Get sequenceEdges.
35772          *
35773          * @returns {IEdgeStatus} Value describing the status of the
35774          * sequence edges.
35775          */
35776         get: function () {
35777             return this._sequenceEdges;
35778         },
35779         enumerable: true,
35780         configurable: true
35781     });
35782     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
35783         /**
35784          * Get sequenceEdges$.
35785          *
35786          * @returns {Observable<IEdgeStatus>} Observable emitting
35787          * values describing the status of the sequence edges.
35788          */
35789         get: function () {
35790             return this._sequenceEdges$;
35791         },
35792         enumerable: true,
35793         configurable: true
35794     });
35795     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
35796         /**
35797          * Get spatialEdges.
35798          *
35799          * @returns {IEdgeStatus} Value describing the status of the
35800          * spatial edges.
35801          */
35802         get: function () {
35803             return this._spatialEdges;
35804         },
35805         enumerable: true,
35806         configurable: true
35807     });
35808     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
35809         /**
35810          * Get spatialEdges$.
35811          *
35812          * @returns {Observable<IEdgeStatus>} Observable emitting
35813          * values describing the status of the spatial edges.
35814          */
35815         get: function () {
35816             return this._spatialEdges$;
35817         },
35818         enumerable: true,
35819         configurable: true
35820     });
35821     /**
35822      * Cache the image and mesh assets.
35823      *
35824      * @param {string} key - Key of the node to cache.
35825      * @param {boolean} pano - Value indicating whether node is a panorama.
35826      * @param {boolean} merged - Value indicating whether node is merged.
35827      * @returns {Observable<NodeCache>} Observable emitting this node
35828      * cache whenever the load status has changed and when the mesh or image
35829      * has been fully loaded.
35830      */
35831     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
35832         var _this = this;
35833         if (this._cachingAssets$ != null) {
35834             return this._cachingAssets$;
35835         }
35836         var imageSize = pano ?
35837             Utils_1.Settings.basePanoramaSize :
35838             Utils_1.Settings.baseImageSize;
35839         this._cachingAssets$ = Observable_1.Observable
35840             .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
35841             _this._loadStatus.loaded = 0;
35842             _this._loadStatus.total = 0;
35843             if (meshStatus) {
35844                 _this._mesh = meshStatus.object;
35845                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
35846                 _this._loadStatus.total += meshStatus.loaded.total;
35847             }
35848             if (imageStatus) {
35849                 _this._image = imageStatus.object;
35850                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
35851                 _this._loadStatus.total += imageStatus.loaded.total;
35852             }
35853             return _this;
35854         })
35855             .finally(function () {
35856             _this._cachingAssets$ = null;
35857         })
35858             .publishReplay(1)
35859             .refCount();
35860         return this._cachingAssets$;
35861     };
35862     /**
35863      * Cache an image with a higher resolution than the current one.
35864      *
35865      * @param {string} key - Key of the node to cache.
35866      * @param {ImageSize} imageSize - The size to cache.
35867      * @returns {Observable<NodeCache>} Observable emitting a single item,
35868      * the node cache, when the image has been cached. If supplied image
35869      * size is not larger than the current image size the node cache is
35870      * returned immediately.
35871      */
35872     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
35873         var _this = this;
35874         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
35875             return Observable_1.Observable.of(this);
35876         }
35877         return this._cacheImage$(key, imageSize)
35878             .first(function (status) {
35879             return status.object != null;
35880         })
35881             .do(function (status) {
35882             _this._disposeImage();
35883             _this._image = status.object;
35884         })
35885             .map(function (imageStatus) {
35886             return _this;
35887         });
35888     };
35889     /**
35890      * Cache the sequence edges.
35891      *
35892      * @param {Array<IEdge>} edges - Sequence edges to cache.
35893      */
35894     NodeCache.prototype.cacheSequenceEdges = function (edges) {
35895         this._sequenceEdges = { cached: true, edges: edges };
35896         this._sequenceEdgesChanged$.next(this._sequenceEdges);
35897     };
35898     /**
35899      * Cache the spatial edges.
35900      *
35901      * @param {Array<IEdge>} edges - Spatial edges to cache.
35902      */
35903     NodeCache.prototype.cacheSpatialEdges = function (edges) {
35904         this._spatialEdges = { cached: true, edges: edges };
35905         this._spatialEdgesChanged$.next(this._spatialEdges);
35906     };
35907     /**
35908      * Dispose the node cache.
35909      *
35910      * @description Disposes all cached assets and unsubscribes to
35911      * all streams.
35912      */
35913     NodeCache.prototype.dispose = function () {
35914         this._sequenceEdgesSubscription.unsubscribe();
35915         this._spatialEdgesSubscription.unsubscribe();
35916         this._disposeImage();
35917         this._mesh = null;
35918         this._loadStatus.loaded = 0;
35919         this._loadStatus.total = 0;
35920         this._sequenceEdges = { cached: false, edges: [] };
35921         this._spatialEdges = { cached: false, edges: [] };
35922         this._sequenceEdgesChanged$.next(this._sequenceEdges);
35923         this._spatialEdgesChanged$.next(this._spatialEdges);
35924         this._disposed = true;
35925         if (this._imageRequest != null) {
35926             this._imageRequest.abort();
35927         }
35928         if (this._meshRequest != null) {
35929             this._meshRequest.abort();
35930         }
35931     };
35932     /**
35933      * Reset the sequence edges.
35934      */
35935     NodeCache.prototype.resetSequenceEdges = function () {
35936         this._sequenceEdges = { cached: false, edges: [] };
35937         this._sequenceEdgesChanged$.next(this._sequenceEdges);
35938     };
35939     /**
35940      * Reset the spatial edges.
35941      */
35942     NodeCache.prototype.resetSpatialEdges = function () {
35943         this._spatialEdges = { cached: false, edges: [] };
35944         this._spatialEdgesChanged$.next(this._spatialEdges);
35945     };
35946     /**
35947      * Cache the image.
35948      *
35949      * @param {string} key - Key of the node to cache.
35950      * @param {boolean} pano - Value indicating whether node is a panorama.
35951      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
35952      * emitting a load status object every time the load status changes
35953      * and completes when the image is fully loaded.
35954      */
35955     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
35956         var _this = this;
35957         return Observable_1.Observable.create(function (subscriber) {
35958             var xmlHTTP = new XMLHttpRequest();
35959             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
35960             xmlHTTP.responseType = "arraybuffer";
35961             xmlHTTP.timeout = 15000;
35962             xmlHTTP.onload = function (pe) {
35963                 if (xmlHTTP.status !== 200) {
35964                     _this._imageRequest = null;
35965                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
35966                     return;
35967                 }
35968                 var image = new Image();
35969                 image.crossOrigin = "Anonymous";
35970                 image.onload = function (e) {
35971                     _this._imageRequest = null;
35972                     if (_this._disposed) {
35973                         window.URL.revokeObjectURL(image.src);
35974                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
35975                         return;
35976                     }
35977                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
35978                     subscriber.complete();
35979                 };
35980                 image.onerror = function (error) {
35981                     _this._imageRequest = null;
35982                     subscriber.error(new Error("Failed to load image (" + key + ")"));
35983                 };
35984                 var blob = new Blob([xmlHTTP.response]);
35985                 image.src = window.URL.createObjectURL(blob);
35986             };
35987             xmlHTTP.onprogress = function (pe) {
35988                 if (_this._disposed) {
35989                     return;
35990                 }
35991                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
35992             };
35993             xmlHTTP.onerror = function (error) {
35994                 _this._imageRequest = null;
35995                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
35996             };
35997             xmlHTTP.ontimeout = function (e) {
35998                 _this._imageRequest = null;
35999                 subscriber.error(new Error("Image request timed out (" + key + ")"));
36000             };
36001             xmlHTTP.onabort = function (event) {
36002                 _this._imageRequest = null;
36003                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
36004             };
36005             _this._imageRequest = xmlHTTP;
36006             xmlHTTP.send(null);
36007         });
36008     };
36009     /**
36010      * Cache the mesh.
36011      *
36012      * @param {string} key - Key of the node to cache.
36013      * @param {boolean} merged - Value indicating whether node is merged.
36014      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
36015      * a load status object every time the load status changes and completes
36016      * when the mesh is fully loaded.
36017      */
36018     NodeCache.prototype._cacheMesh$ = function (key, merged) {
36019         var _this = this;
36020         return Observable_1.Observable.create(function (subscriber) {
36021             if (!merged) {
36022                 subscriber.next(_this._createEmptyMeshLoadStatus());
36023                 subscriber.complete();
36024                 return;
36025             }
36026             var xmlHTTP = new XMLHttpRequest();
36027             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
36028             xmlHTTP.responseType = "arraybuffer";
36029             xmlHTTP.timeout = 15000;
36030             xmlHTTP.onload = function (pe) {
36031                 _this._meshRequest = null;
36032                 if (_this._disposed) {
36033                     return;
36034                 }
36035                 var mesh = xmlHTTP.status === 200 ?
36036                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
36037                     { faces: [], vertices: [] };
36038                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
36039                 subscriber.complete();
36040             };
36041             xmlHTTP.onprogress = function (pe) {
36042                 if (_this._disposed) {
36043                     return;
36044                 }
36045                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
36046             };
36047             xmlHTTP.onerror = function (e) {
36048                 _this._meshRequest = null;
36049                 console.error("Failed to cache mesh (" + key + ")");
36050                 subscriber.next(_this._createEmptyMeshLoadStatus());
36051                 subscriber.complete();
36052             };
36053             xmlHTTP.ontimeout = function (e) {
36054                 _this._meshRequest = null;
36055                 console.error("Mesh request timed out (" + key + ")");
36056                 subscriber.next(_this._createEmptyMeshLoadStatus());
36057                 subscriber.complete();
36058             };
36059             xmlHTTP.onabort = function (e) {
36060                 _this._meshRequest = null;
36061                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
36062             };
36063             _this._meshRequest = xmlHTTP;
36064             xmlHTTP.send(null);
36065         });
36066     };
36067     /**
36068      * Create a load status object with an empty mesh.
36069      *
36070      * @returns {ILoadStatusObject<IMesh>} Load status object
36071      * with empty mesh.
36072      */
36073     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
36074         return {
36075             loaded: { loaded: 0, total: 0 },
36076             object: { faces: [], vertices: [] },
36077         };
36078     };
36079     NodeCache.prototype._disposeImage = function () {
36080         if (this._image != null) {
36081             window.URL.revokeObjectURL(this._image.src);
36082         }
36083         this._image = null;
36084     };
36085     return NodeCache;
36086 }());
36087 exports.NodeCache = NodeCache;
36088 exports.default = NodeCache;
36089
36090 }).call(this,require("buffer").Buffer)
36091
36092 },{"../Graph":234,"../Utils":240,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":72}],337:[function(require,module,exports){
36093 "use strict";
36094 /// <reference path="../../typings/index.d.ts" />
36095 Object.defineProperty(exports, "__esModule", { value: true });
36096 var _ = require("underscore");
36097 /**
36098  * @class Sequence
36099  *
36100  * @classdesc Represents a sequence of ordered nodes.
36101  */
36102 var Sequence = (function () {
36103     /**
36104      * Create a new sequene instance.
36105      *
36106      * @param {ISequence} sequence - Raw sequence data.
36107      */
36108     function Sequence(sequence) {
36109         this._key = sequence.key;
36110         this._keys = sequence.keys;
36111     }
36112     Object.defineProperty(Sequence.prototype, "key", {
36113         /**
36114          * Get key.
36115          *
36116          * @returns {string} Unique sequence key.
36117          */
36118         get: function () {
36119             return this._key;
36120         },
36121         enumerable: true,
36122         configurable: true
36123     });
36124     Object.defineProperty(Sequence.prototype, "keys", {
36125         /**
36126          * Get keys.
36127          *
36128          * @returns {Array<string>} Array of ordered node keys in the sequence.
36129          */
36130         get: function () {
36131             return this._keys;
36132         },
36133         enumerable: true,
36134         configurable: true
36135     });
36136     /**
36137      * Dispose the sequence.
36138      *
36139      * @description Disposes all cached assets.
36140      */
36141     Sequence.prototype.dispose = function () {
36142         this._key = null;
36143         this._keys = null;
36144     };
36145     /**
36146      * Find the next node key in the sequence with respect to
36147      * the provided node key.
36148      *
36149      * @param {string} key - Reference node key.
36150      * @returns {string} Next key in sequence if it exists, null otherwise.
36151      */
36152     Sequence.prototype.findNextKey = function (key) {
36153         var i = _.indexOf(this._keys, key);
36154         if ((i + 1) >= this._keys.length || i === -1) {
36155             return null;
36156         }
36157         else {
36158             return this._keys[i + 1];
36159         }
36160     };
36161     /**
36162      * Find the previous node key in the sequence with respect to
36163      * the provided node key.
36164      *
36165      * @param {string} key - Reference node key.
36166      * @returns {string} Previous key in sequence if it exists, null otherwise.
36167      */
36168     Sequence.prototype.findPrevKey = function (key) {
36169         var i = _.indexOf(this._keys, key);
36170         if (i === 0 || i === -1) {
36171             return null;
36172         }
36173         else {
36174             return this._keys[i - 1];
36175         }
36176     };
36177     return Sequence;
36178 }());
36179 exports.Sequence = Sequence;
36180 exports.default = Sequence;
36181
36182 },{"underscore":182}],338:[function(require,module,exports){
36183 "use strict";
36184 /// <reference path="../../../typings/index.d.ts" />
36185 Object.defineProperty(exports, "__esModule", { value: true });
36186 var THREE = require("three");
36187 var Edge_1 = require("../../Edge");
36188 var Error_1 = require("../../Error");
36189 var Geo_1 = require("../../Geo");
36190 /**
36191  * @class EdgeCalculator
36192  *
36193  * @classdesc Represents a class for calculating node edges.
36194  */
36195 var EdgeCalculator = (function () {
36196     /**
36197      * Create a new edge calculator instance.
36198      *
36199      * @param {EdgeCalculatorSettings} settings - Settings struct.
36200      * @param {EdgeCalculatorDirections} directions - Directions struct.
36201      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
36202      */
36203     function EdgeCalculator(settings, directions, coefficients) {
36204         this._spatial = new Geo_1.Spatial();
36205         this._geoCoords = new Geo_1.GeoCoords();
36206         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
36207         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
36208         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
36209     }
36210     /**
36211      * Returns the potential edges to destination nodes for a set
36212      * of nodes with respect to a source node.
36213      *
36214      * @param {Node} node - Source node.
36215      * @param {Array<Node>} nodes - Potential destination nodes.
36216      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
36217      * be returned even if they do not meet the criteria for a potential edge.
36218      * @throws {ArgumentMapillaryError} If node is not full.
36219      */
36220     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
36221         if (!node.full) {
36222             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36223         }
36224         if (!node.merged) {
36225             return [];
36226         }
36227         var currentDirection = this._spatial.viewingDirection(node.rotation);
36228         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
36229         var potentialEdges = [];
36230         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
36231             var potential = potentialNodes_1[_i];
36232             if (!potential.merged ||
36233                 potential.key === node.key) {
36234                 continue;
36235             }
36236             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
36237             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
36238             var distance = motion.length();
36239             if (distance > this._settings.maxDistance &&
36240                 fallbackKeys.indexOf(potential.key) < 0) {
36241                 continue;
36242             }
36243             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
36244             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
36245             var direction = this._spatial.viewingDirection(potential.rotation);
36246             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
36247             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
36248             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
36249             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
36250             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
36251             var sameSequence = potential.sequenceKey != null &&
36252                 node.sequenceKey != null &&
36253                 potential.sequenceKey === node.sequenceKey;
36254             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
36255                 potential.mergeCC === node.mergeCC;
36256             var sameUser = potential.userKey === node.userKey;
36257             var potentialEdge = {
36258                 capturedAt: potential.capturedAt,
36259                 croppedPano: potential.pano && !potential.fullPano,
36260                 directionChange: directionChange,
36261                 distance: distance,
36262                 fullPano: potential.fullPano,
36263                 key: potential.key,
36264                 motionChange: motionChange,
36265                 rotation: rotation,
36266                 sameMergeCC: sameMergeCC,
36267                 sameSequence: sameSequence,
36268                 sameUser: sameUser,
36269                 sequenceKey: potential.sequenceKey,
36270                 verticalDirectionChange: verticalDirectionChange,
36271                 verticalMotion: verticalMotion,
36272                 worldMotionAzimuth: worldMotionAzimuth,
36273             };
36274             potentialEdges.push(potentialEdge);
36275         }
36276         return potentialEdges;
36277     };
36278     /**
36279      * Computes the sequence edges for a node.
36280      *
36281      * @param {Node} node - Source node.
36282      * @throws {ArgumentMapillaryError} If node is not full.
36283      */
36284     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
36285         if (!node.full) {
36286             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36287         }
36288         if (node.sequenceKey !== sequence.key) {
36289             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
36290         }
36291         var edges = [];
36292         var nextKey = sequence.findNextKey(node.key);
36293         if (nextKey != null) {
36294             edges.push({
36295                 data: {
36296                     direction: Edge_1.EdgeDirection.Next,
36297                     worldMotionAzimuth: Number.NaN,
36298                 },
36299                 from: node.key,
36300                 to: nextKey,
36301             });
36302         }
36303         var prevKey = sequence.findPrevKey(node.key);
36304         if (prevKey != null) {
36305             edges.push({
36306                 data: {
36307                     direction: Edge_1.EdgeDirection.Prev,
36308                     worldMotionAzimuth: Number.NaN,
36309                 },
36310                 from: node.key,
36311                 to: prevKey,
36312             });
36313         }
36314         return edges;
36315     };
36316     /**
36317      * Computes the similar edges for a node.
36318      *
36319      * @description Similar edges for perspective images and cropped panoramas
36320      * look roughly in the same direction and are positioned closed to the node.
36321      * Similar edges for full panoramas only target other full panoramas.
36322      *
36323      * @param {Node} node - Source node.
36324      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
36325      * @throws {ArgumentMapillaryError} If node is not full.
36326      */
36327     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
36328         var _this = this;
36329         if (!node.full) {
36330             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36331         }
36332         var nodeFullPano = node.fullPano;
36333         var sequenceGroups = {};
36334         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
36335             var potentialEdge = potentialEdges_1[_i];
36336             if (potentialEdge.sequenceKey == null) {
36337                 continue;
36338             }
36339             if (potentialEdge.sameSequence ||
36340                 !potentialEdge.sameMergeCC) {
36341                 continue;
36342             }
36343             if (nodeFullPano) {
36344                 if (!potentialEdge.fullPano) {
36345                     continue;
36346                 }
36347             }
36348             else {
36349                 if (!potentialEdge.fullPano &&
36350                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
36351                     continue;
36352                 }
36353             }
36354             if (potentialEdge.distance > this._settings.similarMaxDistance) {
36355                 continue;
36356             }
36357             if (potentialEdge.sameUser &&
36358                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
36359                     this._settings.similarMinTimeDifference) {
36360                 continue;
36361             }
36362             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
36363                 sequenceGroups[potentialEdge.sequenceKey] = [];
36364             }
36365             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
36366         }
36367         var similarEdges = [];
36368         var calculateScore = node.fullPano ?
36369             function (potentialEdge) {
36370                 return potentialEdge.distance;
36371             } :
36372             function (potentialEdge) {
36373                 return _this._coefficients.similarDistance * potentialEdge.distance +
36374                     _this._coefficients.similarRotation * potentialEdge.rotation;
36375             };
36376         for (var sequenceKey in sequenceGroups) {
36377             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
36378                 continue;
36379             }
36380             var lowestScore = Number.MAX_VALUE;
36381             var similarEdge = null;
36382             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
36383                 var potentialEdge = _b[_a];
36384                 var score = calculateScore(potentialEdge);
36385                 if (score < lowestScore) {
36386                     lowestScore = score;
36387                     similarEdge = potentialEdge;
36388                 }
36389             }
36390             if (similarEdge == null) {
36391                 continue;
36392             }
36393             similarEdges.push(similarEdge);
36394         }
36395         return similarEdges
36396             .map(function (potentialEdge) {
36397             return {
36398                 data: {
36399                     direction: Edge_1.EdgeDirection.Similar,
36400                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
36401                 },
36402                 from: node.key,
36403                 to: potentialEdge.key,
36404             };
36405         });
36406     };
36407     /**
36408      * Computes the step edges for a perspective node.
36409      *
36410      * @description Step edge targets can only be other perspective nodes.
36411      * Returns an empty array for cropped and full panoramas.
36412      *
36413      * @param {Node} node - Source node.
36414      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
36415      * @param {string} prevKey - Key of previous node in sequence.
36416      * @param {string} prevKey - Key of next node in sequence.
36417      * @throws {ArgumentMapillaryError} If node is not full.
36418      */
36419     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
36420         if (!node.full) {
36421             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36422         }
36423         var edges = [];
36424         if (node.pano) {
36425             return edges;
36426         }
36427         for (var k in this._directions.steps) {
36428             if (!this._directions.steps.hasOwnProperty(k)) {
36429                 continue;
36430             }
36431             var step = this._directions.steps[k];
36432             var lowestScore = Number.MAX_VALUE;
36433             var edge = null;
36434             var fallback = null;
36435             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
36436                 var potential = potentialEdges_2[_i];
36437                 if (potential.croppedPano || potential.fullPano) {
36438                     continue;
36439                 }
36440                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
36441                     continue;
36442                 }
36443                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
36444                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
36445                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
36446                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
36447                     continue;
36448                 }
36449                 var potentialKey = potential.key;
36450                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
36451                     fallback = potential;
36452                 }
36453                 if (potential.distance > this._settings.stepMaxDistance) {
36454                     continue;
36455                 }
36456                 motionDifference = Math.sqrt(motionDifference * motionDifference +
36457                     potential.verticalMotion * potential.verticalMotion);
36458                 var score = this._coefficients.stepPreferredDistance *
36459                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
36460                     this._settings.stepMaxDistance +
36461                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
36462                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
36463                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
36464                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
36465                 if (score < lowestScore) {
36466                     lowestScore = score;
36467                     edge = potential;
36468                 }
36469             }
36470             edge = edge == null ? fallback : edge;
36471             if (edge != null) {
36472                 edges.push({
36473                     data: {
36474                         direction: step.direction,
36475                         worldMotionAzimuth: edge.worldMotionAzimuth,
36476                     },
36477                     from: node.key,
36478                     to: edge.key,
36479                 });
36480             }
36481         }
36482         return edges;
36483     };
36484     /**
36485      * Computes the turn edges for a perspective node.
36486      *
36487      * @description Turn edge targets can only be other perspective images.
36488      * Returns an empty array for cropped and full panoramas.
36489      *
36490      * @param {Node} node - Source node.
36491      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
36492      * @throws {ArgumentMapillaryError} If node is not full.
36493      */
36494     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
36495         if (!node.full) {
36496             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36497         }
36498         var edges = [];
36499         if (node.pano) {
36500             return edges;
36501         }
36502         for (var k in this._directions.turns) {
36503             if (!this._directions.turns.hasOwnProperty(k)) {
36504                 continue;
36505             }
36506             var turn = this._directions.turns[k];
36507             var lowestScore = Number.MAX_VALUE;
36508             var edge = null;
36509             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
36510                 var potential = potentialEdges_3[_i];
36511                 if (potential.croppedPano || potential.fullPano) {
36512                     continue;
36513                 }
36514                 if (potential.distance > this._settings.turnMaxDistance) {
36515                     continue;
36516                 }
36517                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
36518                     potential.distance < this._settings.turnMaxRigDistance &&
36519                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
36520                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
36521                 var score = void 0;
36522                 if (rig &&
36523                     potential.directionChange * turn.directionChange > 0 &&
36524                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
36525                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
36526                 }
36527                 else {
36528                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
36529                         continue;
36530                     }
36531                     var motionDifference = turn.motionChange ?
36532                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
36533                     motionDifference = Math.sqrt(motionDifference * motionDifference +
36534                         potential.verticalMotion * potential.verticalMotion);
36535                     score =
36536                         this._coefficients.turnDistance * potential.distance /
36537                             this._settings.turnMaxDistance +
36538                             this._coefficients.turnMotion * motionDifference / Math.PI +
36539                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
36540                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
36541                 }
36542                 if (score < lowestScore) {
36543                     lowestScore = score;
36544                     edge = potential;
36545                 }
36546             }
36547             if (edge != null) {
36548                 edges.push({
36549                     data: {
36550                         direction: turn.direction,
36551                         worldMotionAzimuth: edge.worldMotionAzimuth,
36552                     },
36553                     from: node.key,
36554                     to: edge.key,
36555                 });
36556             }
36557         }
36558         return edges;
36559     };
36560     /**
36561      * Computes the pano edges for a perspective node.
36562      *
36563      * @description Perspective to pano edge targets can only be
36564      * full pano nodes. Returns an empty array for cropped and full panoramas.
36565      *
36566      * @param {Node} node - Source node.
36567      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
36568      * @throws {ArgumentMapillaryError} If node is not full.
36569      */
36570     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
36571         if (!node.full) {
36572             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36573         }
36574         if (node.pano) {
36575             return [];
36576         }
36577         var lowestScore = Number.MAX_VALUE;
36578         var edge = null;
36579         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
36580             var potential = potentialEdges_4[_i];
36581             if (!potential.fullPano) {
36582                 continue;
36583             }
36584             var score = this._coefficients.panoPreferredDistance *
36585                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
36586                 this._settings.panoMaxDistance +
36587                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
36588                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
36589             if (score < lowestScore) {
36590                 lowestScore = score;
36591                 edge = potential;
36592             }
36593         }
36594         if (edge == null) {
36595             return [];
36596         }
36597         return [
36598             {
36599                 data: {
36600                     direction: Edge_1.EdgeDirection.Pano,
36601                     worldMotionAzimuth: edge.worldMotionAzimuth,
36602                 },
36603                 from: node.key,
36604                 to: edge.key,
36605             },
36606         ];
36607     };
36608     /**
36609      * Computes the full pano and step edges for a full pano node.
36610      *
36611      * @description Pano to pano edge targets can only be
36612      * full pano nodes. Pano to step edge targets can only be perspective
36613      * nodes.
36614      * Returns an empty array for cropped panoramas and perspective nodes.
36615      *
36616      * @param {Node} node - Source node.
36617      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
36618      * @throws {ArgumentMapillaryError} If node is not full.
36619      */
36620     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
36621         if (!node.full) {
36622             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
36623         }
36624         if (!node.fullPano) {
36625             return [];
36626         }
36627         var panoEdges = [];
36628         var potentialPanos = [];
36629         var potentialSteps = [];
36630         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
36631             var potential = potentialEdges_5[_i];
36632             if (potential.distance > this._settings.panoMaxDistance) {
36633                 continue;
36634             }
36635             if (potential.fullPano) {
36636                 if (potential.distance < this._settings.panoMinDistance) {
36637                     continue;
36638                 }
36639                 potentialPanos.push(potential);
36640             }
36641             else {
36642                 if (potential.croppedPano) {
36643                     continue;
36644                 }
36645                 for (var k in this._directions.panos) {
36646                     if (!this._directions.panos.hasOwnProperty(k)) {
36647                         continue;
36648                     }
36649                     var pano = this._directions.panos[k];
36650                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
36651                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
36652                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
36653                         continue;
36654                     }
36655                     potentialSteps.push([pano.direction, potential]);
36656                     // break if step direction found
36657                     break;
36658                 }
36659             }
36660         }
36661         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
36662         var occupiedAngles = [];
36663         var stepAngles = [];
36664         for (var index = 0; index < this._settings.panoMaxItems; index++) {
36665             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
36666             var lowestScore = Number.MAX_VALUE;
36667             var edge = null;
36668             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
36669                 var potential = potentialPanos_1[_a];
36670                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
36671                 if (Math.abs(motionDifference) > maxRotationDifference) {
36672                     continue;
36673                 }
36674                 var occupiedDifference = Number.MAX_VALUE;
36675                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
36676                     var occupiedAngle = occupiedAngles_1[_b];
36677                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
36678                     if (difference < occupiedDifference) {
36679                         occupiedDifference = difference;
36680                     }
36681                 }
36682                 if (occupiedDifference <= maxRotationDifference) {
36683                     continue;
36684                 }
36685                 var score = this._coefficients.panoPreferredDistance *
36686                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
36687                     this._settings.panoMaxDistance +
36688                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
36689                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
36690                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
36691                 if (score < lowestScore) {
36692                     lowestScore = score;
36693                     edge = potential;
36694                 }
36695             }
36696             if (edge != null) {
36697                 occupiedAngles.push(edge.motionChange);
36698                 panoEdges.push({
36699                     data: {
36700                         direction: Edge_1.EdgeDirection.Pano,
36701                         worldMotionAzimuth: edge.worldMotionAzimuth,
36702                     },
36703                     from: node.key,
36704                     to: edge.key,
36705                 });
36706             }
36707             else {
36708                 stepAngles.push(rotation);
36709             }
36710         }
36711         var occupiedStepAngles = {};
36712         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
36713         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
36714         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
36715         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
36716         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
36717         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
36718             var stepAngle = stepAngles_1[_c];
36719             var occupations = [];
36720             for (var k in this._directions.panos) {
36721                 if (!this._directions.panos.hasOwnProperty(k)) {
36722                     continue;
36723                 }
36724                 var pano = this._directions.panos[k];
36725                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
36726                     .concat(occupiedStepAngles[pano.direction])
36727                     .concat(occupiedStepAngles[pano.prev])
36728                     .concat(occupiedStepAngles[pano.next]);
36729                 var lowestScore = Number.MAX_VALUE;
36730                 var edge = null;
36731                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
36732                     var potential = potentialSteps_1[_d];
36733                     if (potential[0] !== pano.direction) {
36734                         continue;
36735                     }
36736                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
36737                     if (Math.abs(motionChange) > maxRotationDifference) {
36738                         continue;
36739                     }
36740                     var minOccupiedDifference = Number.MAX_VALUE;
36741                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
36742                         var occupiedAngle = allOccupiedAngles_1[_e];
36743                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
36744                         if (occupiedDifference < minOccupiedDifference) {
36745                             minOccupiedDifference = occupiedDifference;
36746                         }
36747                     }
36748                     if (minOccupiedDifference <= maxRotationDifference) {
36749                         continue;
36750                     }
36751                     var score = this._coefficients.panoPreferredDistance *
36752                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
36753                         this._settings.panoMaxDistance +
36754                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
36755                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
36756                     if (score < lowestScore) {
36757                         lowestScore = score;
36758                         edge = potential;
36759                     }
36760                 }
36761                 if (edge != null) {
36762                     occupations.push(edge);
36763                     panoEdges.push({
36764                         data: {
36765                             direction: edge[0],
36766                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
36767                         },
36768                         from: node.key,
36769                         to: edge[1].key,
36770                     });
36771                 }
36772             }
36773             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
36774                 var occupation = occupations_1[_f];
36775                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
36776             }
36777         }
36778         return panoEdges;
36779     };
36780     return EdgeCalculator;
36781 }());
36782 exports.EdgeCalculator = EdgeCalculator;
36783 exports.default = EdgeCalculator;
36784
36785 },{"../../Edge":231,"../../Error":232,"../../Geo":233,"three":180}],339:[function(require,module,exports){
36786 "use strict";
36787 Object.defineProperty(exports, "__esModule", { value: true });
36788 var EdgeCalculatorCoefficients = (function () {
36789     function EdgeCalculatorCoefficients() {
36790         this.panoPreferredDistance = 2;
36791         this.panoMotion = 2;
36792         this.panoSequencePenalty = 1;
36793         this.panoMergeCCPenalty = 4;
36794         this.stepPreferredDistance = 4;
36795         this.stepMotion = 3;
36796         this.stepRotation = 4;
36797         this.stepSequencePenalty = 2;
36798         this.stepMergeCCPenalty = 6;
36799         this.similarDistance = 2;
36800         this.similarRotation = 3;
36801         this.turnDistance = 4;
36802         this.turnMotion = 2;
36803         this.turnSequencePenalty = 1;
36804         this.turnMergeCCPenalty = 4;
36805     }
36806     return EdgeCalculatorCoefficients;
36807 }());
36808 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
36809 exports.default = EdgeCalculatorCoefficients;
36810
36811 },{}],340:[function(require,module,exports){
36812 "use strict";
36813 Object.defineProperty(exports, "__esModule", { value: true });
36814 var Edge_1 = require("../../Edge");
36815 var EdgeCalculatorDirections = (function () {
36816     function EdgeCalculatorDirections() {
36817         this.steps = {};
36818         this.turns = {};
36819         this.panos = {};
36820         this.steps[Edge_1.EdgeDirection.StepForward] = {
36821             direction: Edge_1.EdgeDirection.StepForward,
36822             motionChange: 0,
36823             useFallback: true,
36824         };
36825         this.steps[Edge_1.EdgeDirection.StepBackward] = {
36826             direction: Edge_1.EdgeDirection.StepBackward,
36827             motionChange: Math.PI,
36828             useFallback: true,
36829         };
36830         this.steps[Edge_1.EdgeDirection.StepLeft] = {
36831             direction: Edge_1.EdgeDirection.StepLeft,
36832             motionChange: Math.PI / 2,
36833             useFallback: false,
36834         };
36835         this.steps[Edge_1.EdgeDirection.StepRight] = {
36836             direction: Edge_1.EdgeDirection.StepRight,
36837             motionChange: -Math.PI / 2,
36838             useFallback: false,
36839         };
36840         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
36841             direction: Edge_1.EdgeDirection.TurnLeft,
36842             directionChange: Math.PI / 2,
36843             motionChange: Math.PI / 4,
36844         };
36845         this.turns[Edge_1.EdgeDirection.TurnRight] = {
36846             direction: Edge_1.EdgeDirection.TurnRight,
36847             directionChange: -Math.PI / 2,
36848             motionChange: -Math.PI / 4,
36849         };
36850         this.turns[Edge_1.EdgeDirection.TurnU] = {
36851             direction: Edge_1.EdgeDirection.TurnU,
36852             directionChange: Math.PI,
36853             motionChange: null,
36854         };
36855         this.panos[Edge_1.EdgeDirection.StepForward] = {
36856             direction: Edge_1.EdgeDirection.StepForward,
36857             directionChange: 0,
36858             next: Edge_1.EdgeDirection.StepLeft,
36859             prev: Edge_1.EdgeDirection.StepRight,
36860         };
36861         this.panos[Edge_1.EdgeDirection.StepBackward] = {
36862             direction: Edge_1.EdgeDirection.StepBackward,
36863             directionChange: Math.PI,
36864             next: Edge_1.EdgeDirection.StepRight,
36865             prev: Edge_1.EdgeDirection.StepLeft,
36866         };
36867         this.panos[Edge_1.EdgeDirection.StepLeft] = {
36868             direction: Edge_1.EdgeDirection.StepLeft,
36869             directionChange: Math.PI / 2,
36870             next: Edge_1.EdgeDirection.StepBackward,
36871             prev: Edge_1.EdgeDirection.StepForward,
36872         };
36873         this.panos[Edge_1.EdgeDirection.StepRight] = {
36874             direction: Edge_1.EdgeDirection.StepRight,
36875             directionChange: -Math.PI / 2,
36876             next: Edge_1.EdgeDirection.StepForward,
36877             prev: Edge_1.EdgeDirection.StepBackward,
36878         };
36879     }
36880     return EdgeCalculatorDirections;
36881 }());
36882 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
36883
36884 },{"../../Edge":231}],341:[function(require,module,exports){
36885 "use strict";
36886 Object.defineProperty(exports, "__esModule", { value: true });
36887 var EdgeCalculatorSettings = (function () {
36888     function EdgeCalculatorSettings() {
36889         this.panoMinDistance = 0.1;
36890         this.panoMaxDistance = 20;
36891         this.panoPreferredDistance = 5;
36892         this.panoMaxItems = 4;
36893         this.panoMaxStepTurnChange = Math.PI / 8;
36894         this.rotationMaxDistance = this.turnMaxRigDistance;
36895         this.rotationMaxDirectionChange = Math.PI / 6;
36896         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
36897         this.similarMaxDirectionChange = Math.PI / 8;
36898         this.similarMaxDistance = 12;
36899         this.similarMinTimeDifference = 12 * 3600 * 1000;
36900         this.stepMaxDistance = 20;
36901         this.stepMaxDirectionChange = Math.PI / 6;
36902         this.stepMaxDrift = Math.PI / 6;
36903         this.stepPreferredDistance = 4;
36904         this.turnMaxDistance = 15;
36905         this.turnMaxDirectionChange = 2 * Math.PI / 9;
36906         this.turnMaxRigDistance = 0.65;
36907         this.turnMinRigDirectionChange = Math.PI / 6;
36908     }
36909     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
36910         get: function () {
36911             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
36912         },
36913         enumerable: true,
36914         configurable: true
36915     });
36916     return EdgeCalculatorSettings;
36917 }());
36918 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
36919 exports.default = EdgeCalculatorSettings;
36920
36921 },{}],342:[function(require,module,exports){
36922 "use strict";
36923 Object.defineProperty(exports, "__esModule", { value: true });
36924 /**
36925  * Enumeration for edge directions
36926  * @enum {number}
36927  * @readonly
36928  * @description Directions for edges in node graph describing
36929  * sequence, spatial and node type relations between nodes.
36930  */
36931 var EdgeDirection;
36932 (function (EdgeDirection) {
36933     /**
36934      * Next node in the sequence.
36935      */
36936     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
36937     /**
36938      * Previous node in the sequence.
36939      */
36940     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
36941     /**
36942      * Step to the left keeping viewing direction.
36943      */
36944     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
36945     /**
36946      * Step to the right keeping viewing direction.
36947      */
36948     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
36949     /**
36950      * Step forward keeping viewing direction.
36951      */
36952     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
36953     /**
36954      * Step backward keeping viewing direction.
36955      */
36956     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
36957     /**
36958      * Turn 90 degrees counter clockwise.
36959      */
36960     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
36961     /**
36962      * Turn 90 degrees clockwise.
36963      */
36964     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
36965     /**
36966      * Turn 180 degrees.
36967      */
36968     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
36969     /**
36970      * Panorama in general direction.
36971      */
36972     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
36973     /**
36974      * Looking in roughly the same direction at rougly the same position.
36975      */
36976     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
36977 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
36978
36979 },{}],343:[function(require,module,exports){
36980 "use strict";
36981 /// <reference path="../../typings/index.d.ts" />
36982 Object.defineProperty(exports, "__esModule", { value: true });
36983 var _ = require("underscore");
36984 var vd = require("virtual-dom");
36985 var Subject_1 = require("rxjs/Subject");
36986 require("rxjs/add/operator/combineLatest");
36987 require("rxjs/add/operator/distinctUntilChanged");
36988 require("rxjs/add/operator/filter");
36989 require("rxjs/add/operator/map");
36990 require("rxjs/add/operator/pluck");
36991 require("rxjs/add/operator/scan");
36992 var Render_1 = require("../Render");
36993 var DOMRenderer = (function () {
36994     function DOMRenderer(element, renderService, currentFrame$) {
36995         this._adaptiveOperation$ = new Subject_1.Subject();
36996         this._render$ = new Subject_1.Subject();
36997         this._renderAdaptive$ = new Subject_1.Subject();
36998         this._renderService = renderService;
36999         this._currentFrame$ = currentFrame$;
37000         var rootNode = vd.create(vd.h("div.domRenderer", []));
37001         element.appendChild(rootNode);
37002         this._offset$ = this._adaptiveOperation$
37003             .scan(function (adaptive, operation) {
37004             return operation(adaptive);
37005         }, {
37006             elementHeight: element.offsetHeight,
37007             elementWidth: element.offsetWidth,
37008             imageAspect: 0,
37009             renderMode: Render_1.RenderMode.Fill,
37010         })
37011             .filter(function (adaptive) {
37012             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
37013         })
37014             .map(function (adaptive) {
37015             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
37016             var ratio = adaptive.imageAspect / elementAspect;
37017             var verticalOffset = 0;
37018             var horizontalOffset = 0;
37019             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
37020                 if (adaptive.imageAspect > elementAspect) {
37021                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
37022                 }
37023                 else {
37024                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
37025                 }
37026             }
37027             else {
37028                 if (adaptive.imageAspect > elementAspect) {
37029                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
37030                 }
37031                 else {
37032                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
37033                 }
37034             }
37035             return {
37036                 bottom: verticalOffset,
37037                 left: horizontalOffset,
37038                 right: horizontalOffset,
37039                 top: verticalOffset,
37040             };
37041         });
37042         this._currentFrame$
37043             .filter(function (frame) {
37044             return frame.state.currentNode != null;
37045         })
37046             .distinctUntilChanged(function (k1, k2) {
37047             return k1 === k2;
37048         }, function (frame) {
37049             return frame.state.currentNode.key;
37050         })
37051             .map(function (frame) {
37052             return frame.state.currentTransform.basicAspect;
37053         })
37054             .map(function (aspect) {
37055             return function (adaptive) {
37056                 adaptive.imageAspect = aspect;
37057                 return adaptive;
37058             };
37059         })
37060             .subscribe(this._adaptiveOperation$);
37061         this._renderAdaptive$
37062             .scan(function (vNodeHashes, vNodeHash) {
37063             if (vNodeHash.vnode == null) {
37064                 delete vNodeHashes[vNodeHash.name];
37065             }
37066             else {
37067                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
37068             }
37069             return vNodeHashes;
37070         }, {})
37071             .combineLatest(this._offset$)
37072             .map(function (vo) {
37073             var vNodes = _.values(vo[0]);
37074             var offset = vo[1];
37075             var properties = {
37076                 style: {
37077                     bottom: offset.bottom + "px",
37078                     left: offset.left + "px",
37079                     "pointer-events": "none",
37080                     position: "absolute",
37081                     right: offset.right + "px",
37082                     top: offset.top + "px",
37083                 },
37084             };
37085             return {
37086                 name: "adaptiveDomRenderer",
37087                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
37088             };
37089         })
37090             .subscribe(this._render$);
37091         this._vNode$ = this._render$
37092             .scan(function (vNodeHashes, vNodeHash) {
37093             if (vNodeHash.vnode == null) {
37094                 delete vNodeHashes[vNodeHash.name];
37095             }
37096             else {
37097                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
37098             }
37099             return vNodeHashes;
37100         }, {})
37101             .map(function (vNodeHashes) {
37102             var vNodes = _.values(vNodeHashes);
37103             return vd.h("div.domRenderer", vNodes);
37104         });
37105         this._vPatch$ = this._vNode$
37106             .scan(function (nodePatch, vNode) {
37107             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
37108             nodePatch.vnode = vNode;
37109             return nodePatch;
37110         }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
37111             .pluck("vpatch");
37112         this._element$ = this._vPatch$
37113             .scan(function (oldElement, vPatch) {
37114             return vd.patch(oldElement, vPatch);
37115         }, rootNode)
37116             .publishReplay(1)
37117             .refCount();
37118         this._element$.subscribe(function () { });
37119         this._renderService.size$
37120             .map(function (size) {
37121             return function (adaptive) {
37122                 adaptive.elementWidth = size.width;
37123                 adaptive.elementHeight = size.height;
37124                 return adaptive;
37125             };
37126         })
37127             .subscribe(this._adaptiveOperation$);
37128         this._renderService.renderMode$
37129             .map(function (renderMode) {
37130             return function (adaptive) {
37131                 adaptive.renderMode = renderMode;
37132                 return adaptive;
37133             };
37134         })
37135             .subscribe(this._adaptiveOperation$);
37136     }
37137     Object.defineProperty(DOMRenderer.prototype, "element$", {
37138         get: function () {
37139             return this._element$;
37140         },
37141         enumerable: true,
37142         configurable: true
37143     });
37144     Object.defineProperty(DOMRenderer.prototype, "render$", {
37145         get: function () {
37146             return this._render$;
37147         },
37148         enumerable: true,
37149         configurable: true
37150     });
37151     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
37152         get: function () {
37153             return this._renderAdaptive$;
37154         },
37155         enumerable: true,
37156         configurable: true
37157     });
37158     DOMRenderer.prototype.clear = function (name) {
37159         this._renderAdaptive$.next({ name: name, vnode: null });
37160         this._render$.next({ name: name, vnode: null });
37161     };
37162     return DOMRenderer;
37163 }());
37164 exports.DOMRenderer = DOMRenderer;
37165 exports.default = DOMRenderer;
37166
37167 },{"../Render":236,"rxjs/Subject":34,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":74,"underscore":182,"virtual-dom":186}],344:[function(require,module,exports){
37168 "use strict";
37169 Object.defineProperty(exports, "__esModule", { value: true });
37170 var GLRenderStage;
37171 (function (GLRenderStage) {
37172     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
37173     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
37174 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
37175 exports.default = GLRenderStage;
37176
37177 },{}],345:[function(require,module,exports){
37178 "use strict";
37179 /// <reference path="../../typings/index.d.ts" />
37180 Object.defineProperty(exports, "__esModule", { value: true });
37181 var THREE = require("three");
37182 var Observable_1 = require("rxjs/Observable");
37183 var Subject_1 = require("rxjs/Subject");
37184 require("rxjs/add/observable/combineLatest");
37185 require("rxjs/add/operator/distinctUntilChanged");
37186 require("rxjs/add/operator/filter");
37187 require("rxjs/add/operator/first");
37188 require("rxjs/add/operator/map");
37189 require("rxjs/add/operator/merge");
37190 require("rxjs/add/operator/mergeMap");
37191 require("rxjs/add/operator/scan");
37192 require("rxjs/add/operator/share");
37193 require("rxjs/add/operator/startWith");
37194 var Render_1 = require("../Render");
37195 var Utils_1 = require("../Utils");
37196 var GLRenderer = (function () {
37197     function GLRenderer(canvasContainer, renderService, dom) {
37198         var _this = this;
37199         this._renderFrame$ = new Subject_1.Subject();
37200         this._renderCameraOperation$ = new Subject_1.Subject();
37201         this._render$ = new Subject_1.Subject();
37202         this._clear$ = new Subject_1.Subject();
37203         this._renderOperation$ = new Subject_1.Subject();
37204         this._rendererOperation$ = new Subject_1.Subject();
37205         this._eraserOperation$ = new Subject_1.Subject();
37206         this._renderService = renderService;
37207         this._dom = !!dom ? dom : new Utils_1.DOM();
37208         this._renderer$ = this._rendererOperation$
37209             .scan(function (renderer, operation) {
37210             return operation(renderer);
37211         }, { needsRender: false, renderer: null });
37212         this._renderCollection$ = this._renderOperation$
37213             .scan(function (hashes, operation) {
37214             return operation(hashes);
37215         }, {})
37216             .share();
37217         this._renderCamera$ = this._renderCameraOperation$
37218             .scan(function (rc, operation) {
37219             return operation(rc);
37220         }, { frameId: -1, needsRender: false, perspective: null });
37221         this._eraser$ = this._eraserOperation$
37222             .startWith(function (eraser) {
37223             return eraser;
37224         })
37225             .scan(function (eraser, operation) {
37226             return operation(eraser);
37227         }, { needsRender: false });
37228         Observable_1.Observable
37229             .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
37230             var renders = Object.keys(hashes)
37231                 .map(function (key) {
37232                 return hashes[key];
37233             });
37234             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
37235         })
37236             .filter(function (co) {
37237             var needsRender = co.renderer.needsRender ||
37238                 co.camera.needsRender ||
37239                 co.eraser.needsRender;
37240             var frameId = co.camera.frameId;
37241             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
37242                 var render = _a[_i];
37243                 if (render.frameId !== frameId) {
37244                     return false;
37245                 }
37246                 needsRender = needsRender || render.needsRender;
37247             }
37248             return needsRender;
37249         })
37250             .distinctUntilChanged(function (n1, n2) {
37251             return n1 === n2;
37252         }, function (co) {
37253             return co.eraser.needsRender ? -1 : co.camera.frameId;
37254         })
37255             .subscribe(function (co) {
37256             co.renderer.needsRender = false;
37257             co.camera.needsRender = false;
37258             co.eraser.needsRender = false;
37259             var perspectiveCamera = co.camera.perspective;
37260             var backgroundRenders = [];
37261             var foregroundRenders = [];
37262             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
37263                 var render = _a[_i];
37264                 if (render.stage === Render_1.GLRenderStage.Background) {
37265                     backgroundRenders.push(render.render);
37266                 }
37267                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
37268                     foregroundRenders.push(render.render);
37269                 }
37270             }
37271             var renderer = co.renderer.renderer;
37272             renderer.clear();
37273             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
37274                 var render = backgroundRenders_1[_b];
37275                 render(perspectiveCamera, renderer);
37276             }
37277             renderer.clearDepth();
37278             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
37279                 var render = foregroundRenders_1[_c];
37280                 render(perspectiveCamera, renderer);
37281             }
37282         });
37283         this._renderFrame$
37284             .map(function (rc) {
37285             return function (irc) {
37286                 irc.frameId = rc.frameId;
37287                 irc.perspective = rc.perspective;
37288                 if (rc.changed === true) {
37289                     irc.needsRender = true;
37290                 }
37291                 return irc;
37292             };
37293         })
37294             .subscribe(this._renderCameraOperation$);
37295         this._renderFrameSubscribe();
37296         var renderHash$ = this._render$
37297             .map(function (hash) {
37298             return function (hashes) {
37299                 hashes[hash.name] = hash.render;
37300                 return hashes;
37301             };
37302         });
37303         var clearHash$ = this._clear$
37304             .map(function (name) {
37305             return function (hashes) {
37306                 delete hashes[name];
37307                 return hashes;
37308             };
37309         });
37310         Observable_1.Observable
37311             .merge(renderHash$, clearHash$)
37312             .subscribe(this._renderOperation$);
37313         this._webGLRenderer$ = this._render$
37314             .first()
37315             .map(function (hash) {
37316             var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
37317             canvas.style.position = "absolute";
37318             canvas.setAttribute("tabindex", "0");
37319             canvasContainer.appendChild(canvas);
37320             var element = renderService.element;
37321             var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
37322             webGLRenderer.setPixelRatio(window.devicePixelRatio);
37323             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
37324             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
37325             webGLRenderer.autoClear = false;
37326             return webGLRenderer;
37327         })
37328             .publishReplay(1)
37329             .refCount();
37330         this._webGLRenderer$.subscribe(function () { });
37331         var createRenderer$ = this._webGLRenderer$
37332             .first()
37333             .map(function (webGLRenderer) {
37334             return function (renderer) {
37335                 renderer.needsRender = true;
37336                 renderer.renderer = webGLRenderer;
37337                 return renderer;
37338             };
37339         });
37340         var resizeRenderer$ = this._renderService.size$
37341             .map(function (size) {
37342             return function (renderer) {
37343                 if (renderer.renderer == null) {
37344                     return renderer;
37345                 }
37346                 renderer.renderer.setSize(size.width, size.height);
37347                 renderer.needsRender = true;
37348                 return renderer;
37349             };
37350         });
37351         var clearRenderer$ = this._clear$
37352             .map(function (name) {
37353             return function (renderer) {
37354                 if (renderer.renderer == null) {
37355                     return renderer;
37356                 }
37357                 renderer.needsRender = true;
37358                 return renderer;
37359             };
37360         });
37361         Observable_1.Observable
37362             .merge(createRenderer$, resizeRenderer$, clearRenderer$)
37363             .subscribe(this._rendererOperation$);
37364         var renderCollectionEmpty$ = this._renderCollection$
37365             .filter(function (hashes) {
37366             return Object.keys(hashes).length === 0;
37367         })
37368             .share();
37369         renderCollectionEmpty$
37370             .subscribe(function (hashes) {
37371             if (_this._renderFrameSubscription == null) {
37372                 return;
37373             }
37374             _this._renderFrameSubscription.unsubscribe();
37375             _this._renderFrameSubscription = null;
37376             _this._renderFrameSubscribe();
37377         });
37378         renderCollectionEmpty$
37379             .map(function (hashes) {
37380             return function (eraser) {
37381                 eraser.needsRender = true;
37382                 return eraser;
37383             };
37384         })
37385             .subscribe(this._eraserOperation$);
37386     }
37387     Object.defineProperty(GLRenderer.prototype, "render$", {
37388         get: function () {
37389             return this._render$;
37390         },
37391         enumerable: true,
37392         configurable: true
37393     });
37394     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
37395         get: function () {
37396             return this._webGLRenderer$;
37397         },
37398         enumerable: true,
37399         configurable: true
37400     });
37401     GLRenderer.prototype.clear = function (name) {
37402         this._clear$.next(name);
37403     };
37404     GLRenderer.prototype._renderFrameSubscribe = function () {
37405         var _this = this;
37406         this._render$
37407             .first()
37408             .map(function (renderHash) {
37409             return function (irc) {
37410                 irc.needsRender = true;
37411                 return irc;
37412             };
37413         })
37414             .subscribe(function (operation) {
37415             _this._renderCameraOperation$.next(operation);
37416         });
37417         this._renderFrameSubscription = this._render$
37418             .first()
37419             .mergeMap(function (hash) {
37420             return _this._renderService.renderCameraFrame$;
37421         })
37422             .subscribe(this._renderFrame$);
37423     };
37424     return GLRenderer;
37425 }());
37426 exports.GLRenderer = GLRenderer;
37427 exports.default = GLRenderer;
37428
37429 },{"../Render":236,"../Utils":240,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":74,"rxjs/add/operator/share":75,"rxjs/add/operator/startWith":79,"three":180}],346:[function(require,module,exports){
37430 "use strict";
37431 /// <reference path="../../typings/index.d.ts" />
37432 Object.defineProperty(exports, "__esModule", { value: true });
37433 var THREE = require("three");
37434 var Geo_1 = require("../Geo");
37435 var Render_1 = require("../Render");
37436 var RenderCamera = (function () {
37437     function RenderCamera(elementWidth, elementHeight, renderMode) {
37438         this.alpha = -1;
37439         this.zoom = 0;
37440         this._frameId = -1;
37441         this._changed = false;
37442         this._changedForFrame = -1;
37443         this.currentAspect = 1;
37444         this.currentPano = false;
37445         this.previousAspect = 1;
37446         this.previousPano = false;
37447         this.renderMode = renderMode;
37448         this._spatial = new Geo_1.Spatial();
37449         this._camera = new Geo_1.Camera();
37450         var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
37451         this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
37452         this._perspective.matrixAutoUpdate = false;
37453         this._rotation = { phi: 0, theta: 0 };
37454     }
37455     Object.defineProperty(RenderCamera.prototype, "camera", {
37456         get: function () {
37457             return this._camera;
37458         },
37459         enumerable: true,
37460         configurable: true
37461     });
37462     Object.defineProperty(RenderCamera.prototype, "changed", {
37463         get: function () {
37464             return this.frameId === this._changedForFrame;
37465         },
37466         enumerable: true,
37467         configurable: true
37468     });
37469     Object.defineProperty(RenderCamera.prototype, "frameId", {
37470         get: function () {
37471             return this._frameId;
37472         },
37473         set: function (value) {
37474             this._frameId = value;
37475             if (this._changed) {
37476                 this._changed = false;
37477                 this._changedForFrame = value;
37478             }
37479         },
37480         enumerable: true,
37481         configurable: true
37482     });
37483     Object.defineProperty(RenderCamera.prototype, "perspective", {
37484         get: function () {
37485             return this._perspective;
37486         },
37487         enumerable: true,
37488         configurable: true
37489     });
37490     Object.defineProperty(RenderCamera.prototype, "rotation", {
37491         get: function () {
37492             return this._rotation;
37493         },
37494         enumerable: true,
37495         configurable: true
37496     });
37497     RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
37498         var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
37499         this._perspective.aspect = perspectiveCameraAspect;
37500         this._changed = true;
37501     };
37502     RenderCamera.prototype.updateProjection = function () {
37503         var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
37504         var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
37505         var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
37506         var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
37507         this._perspective.fov = verticalFov;
37508         this._perspective.updateProjectionMatrix();
37509         this._changed = true;
37510     };
37511     RenderCamera.prototype.updatePerspective = function (camera) {
37512         this._perspective.up.copy(camera.up);
37513         this._perspective.position.copy(camera.position);
37514         this._perspective.lookAt(camera.lookat);
37515         this._perspective.updateMatrix();
37516         this._perspective.updateMatrixWorld(false);
37517         this._changed = true;
37518     };
37519     RenderCamera.prototype.updateRotation = function (camera) {
37520         this._rotation = this._getRotation(camera);
37521     };
37522     RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
37523         return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
37524     };
37525     RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
37526         if (pano) {
37527             return 1;
37528         }
37529         var coeff = Math.max(1, 1 / nodeAspect);
37530         var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
37531             nodeAspect > perspectiveCameraAspect :
37532             nodeAspect < perspectiveCameraAspect;
37533         var aspect = usePerspective ?
37534             coeff * perspectiveCameraAspect :
37535             coeff * nodeAspect;
37536         return aspect;
37537     };
37538     RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
37539         return elementWidth === 0 ? 0 : elementWidth / elementHeight;
37540     };
37541     RenderCamera.prototype._getRotation = function (camera) {
37542         var direction = camera.lookat.clone().sub(camera.position);
37543         var up = camera.up.clone();
37544         var upProjection = direction.clone().dot(up);
37545         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
37546         var phi = Math.atan2(planeProjection.y, planeProjection.x);
37547         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
37548         return { phi: phi, theta: theta };
37549     };
37550     return RenderCamera;
37551 }());
37552 exports.RenderCamera = RenderCamera;
37553 exports.default = RenderCamera;
37554
37555 },{"../Geo":233,"../Render":236,"three":180}],347:[function(require,module,exports){
37556 "use strict";
37557 Object.defineProperty(exports, "__esModule", { value: true });
37558 /**
37559  * Enumeration for render mode
37560  * @enum {number}
37561  * @readonly
37562  * @description Modes for specifying how rendering is done
37563  * in the viewer. All modes preserves the original aspect
37564  * ratio of the images.
37565  */
37566 var RenderMode;
37567 (function (RenderMode) {
37568     /**
37569      * Displays all content within the viewer.
37570      *
37571      * @description Black bars shown on both
37572      * sides of the content. Bars are shown
37573      * either below and above or to the left
37574      * and right of the content depending on
37575      * the aspect ratio relation between the
37576      * image and the viewer.
37577      */
37578     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
37579     /**
37580      * Fills the viewer by cropping content.
37581      *
37582      * @description Cropping is done either
37583      * in horizontal or vertical direction
37584      * depending on the aspect ratio relation
37585      * between the image and the viewer.
37586      */
37587     RenderMode[RenderMode["Fill"] = 1] = "Fill";
37588 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
37589 exports.default = RenderMode;
37590
37591 },{}],348:[function(require,module,exports){
37592 "use strict";
37593 /// <reference path="../../typings/index.d.ts" />
37594 Object.defineProperty(exports, "__esModule", { value: true });
37595 var Subject_1 = require("rxjs/Subject");
37596 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37597 require("rxjs/add/observable/combineLatest");
37598 require("rxjs/add/operator/do");
37599 require("rxjs/add/operator/filter");
37600 require("rxjs/add/operator/map");
37601 require("rxjs/add/operator/publishReplay");
37602 require("rxjs/add/operator/scan");
37603 require("rxjs/add/operator/skip");
37604 require("rxjs/add/operator/startWith");
37605 require("rxjs/add/operator/withLatestFrom");
37606 var Geo_1 = require("../Geo");
37607 var Render_1 = require("../Render");
37608 var RenderService = (function () {
37609     function RenderService(element, currentFrame$, renderMode) {
37610         var _this = this;
37611         this._element = element;
37612         this._currentFrame$ = currentFrame$;
37613         this._spatial = new Geo_1.Spatial();
37614         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
37615         this._resize$ = new Subject_1.Subject();
37616         this._renderCameraOperation$ = new Subject_1.Subject();
37617         this._size$ =
37618             new BehaviorSubject_1.BehaviorSubject({
37619                 height: this._element.offsetHeight,
37620                 width: this._element.offsetWidth,
37621             });
37622         this._resize$
37623             .map(function () {
37624             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
37625         })
37626             .subscribe(this._size$);
37627         this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
37628         this._renderCameraHolder$ = this._renderCameraOperation$
37629             .startWith(function (rc) {
37630             return rc;
37631         })
37632             .scan(function (rc, operation) {
37633             return operation(rc);
37634         }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
37635             .publishReplay(1)
37636             .refCount();
37637         this._renderCameraFrame$ = this._currentFrame$
37638             .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
37639             return [frame, renderCamera];
37640         })
37641             .do(function (args) {
37642             var frame = args[0];
37643             var rc = args[1];
37644             var camera = frame.state.camera;
37645             if (rc.alpha !== frame.state.alpha ||
37646                 rc.zoom !== frame.state.zoom ||
37647                 rc.camera.diff(camera) > 1e-9) {
37648                 var currentTransform = frame.state.currentTransform;
37649                 var previousTransform = frame.state.previousTransform != null ?
37650                     frame.state.previousTransform :
37651                     frame.state.currentTransform;
37652                 var previousNode = frame.state.previousNode != null ?
37653                     frame.state.previousNode :
37654                     frame.state.currentNode;
37655                 rc.currentAspect = currentTransform.basicAspect;
37656                 rc.currentPano = frame.state.currentNode.pano;
37657                 rc.previousAspect = previousTransform.basicAspect;
37658                 rc.previousPano = previousNode.pano;
37659                 rc.alpha = frame.state.alpha;
37660                 rc.zoom = frame.state.zoom;
37661                 rc.camera.copy(camera);
37662                 rc.updatePerspective(camera);
37663                 rc.updateRotation(camera);
37664                 rc.updateProjection();
37665             }
37666             rc.frameId = frame.id;
37667         })
37668             .map(function (args) {
37669             return args[1];
37670         })
37671             .publishReplay(1)
37672             .refCount();
37673         this._renderCamera$ = this._renderCameraFrame$
37674             .filter(function (rc) {
37675             return rc.changed;
37676         })
37677             .publishReplay(1)
37678             .refCount();
37679         this._bearing$ = this._renderCamera$
37680             .map(function (renderCamera) {
37681             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
37682             return _this._spatial.wrap(bearing, 0, 360);
37683         })
37684             .publishReplay(1)
37685             .refCount();
37686         this._size$
37687             .skip(1)
37688             .map(function (size) {
37689             return function (rc) {
37690                 rc.updateAspect(size.width, size.height);
37691                 rc.updateProjection();
37692                 return rc;
37693             };
37694         })
37695             .subscribe(this._renderCameraOperation$);
37696         this._renderMode$
37697             .skip(1)
37698             .map(function (rm) {
37699             return function (rc) {
37700                 rc.renderMode = rm;
37701                 rc.updateProjection();
37702                 return rc;
37703             };
37704         })
37705             .subscribe(this._renderCameraOperation$);
37706         this._bearing$.subscribe(function () { });
37707         this._renderCameraHolder$.subscribe(function () { });
37708         this._size$.subscribe(function () { });
37709         this._renderMode$.subscribe(function () { });
37710         this._renderCamera$.subscribe(function () { });
37711         this._renderCameraFrame$.subscribe(function () { });
37712     }
37713     Object.defineProperty(RenderService.prototype, "bearing$", {
37714         get: function () {
37715             return this._bearing$;
37716         },
37717         enumerable: true,
37718         configurable: true
37719     });
37720     Object.defineProperty(RenderService.prototype, "element", {
37721         get: function () {
37722             return this._element;
37723         },
37724         enumerable: true,
37725         configurable: true
37726     });
37727     Object.defineProperty(RenderService.prototype, "resize$", {
37728         get: function () {
37729             return this._resize$;
37730         },
37731         enumerable: true,
37732         configurable: true
37733     });
37734     Object.defineProperty(RenderService.prototype, "size$", {
37735         get: function () {
37736             return this._size$;
37737         },
37738         enumerable: true,
37739         configurable: true
37740     });
37741     Object.defineProperty(RenderService.prototype, "renderMode$", {
37742         get: function () {
37743             return this._renderMode$;
37744         },
37745         enumerable: true,
37746         configurable: true
37747     });
37748     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
37749         get: function () {
37750             return this._renderCameraFrame$;
37751         },
37752         enumerable: true,
37753         configurable: true
37754     });
37755     Object.defineProperty(RenderService.prototype, "renderCamera$", {
37756         get: function () {
37757             return this._renderCamera$;
37758         },
37759         enumerable: true,
37760         configurable: true
37761     });
37762     return RenderService;
37763 }());
37764 exports.RenderService = RenderService;
37765 exports.default = RenderService;
37766
37767 },{"../Geo":233,"../Render":236,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/skip":76,"rxjs/add/operator/startWith":79,"rxjs/add/operator/withLatestFrom":85}],349:[function(require,module,exports){
37768 "use strict";
37769 Object.defineProperty(exports, "__esModule", { value: true });
37770 var State;
37771 (function (State) {
37772     State[State["Traversing"] = 0] = "Traversing";
37773     State[State["Waiting"] = 1] = "Waiting";
37774 })(State = exports.State || (exports.State = {}));
37775 exports.default = State;
37776
37777 },{}],350:[function(require,module,exports){
37778 "use strict";
37779 Object.defineProperty(exports, "__esModule", { value: true });
37780 var State_1 = require("../State");
37781 var Geo_1 = require("../Geo");
37782 var StateContext = (function () {
37783     function StateContext() {
37784         this._state = new State_1.TraversingState({
37785             alpha: 1,
37786             camera: new Geo_1.Camera(),
37787             currentIndex: -1,
37788             reference: { alt: 0, lat: 0, lon: 0 },
37789             trajectory: [],
37790             zoom: 0,
37791         });
37792     }
37793     StateContext.prototype.traverse = function () {
37794         this._state = this._state.traverse();
37795     };
37796     StateContext.prototype.wait = function () {
37797         this._state = this._state.wait();
37798     };
37799     Object.defineProperty(StateContext.prototype, "state", {
37800         get: function () {
37801             if (this._state instanceof State_1.TraversingState) {
37802                 return State_1.State.Traversing;
37803             }
37804             else if (this._state instanceof State_1.WaitingState) {
37805                 return State_1.State.Waiting;
37806             }
37807             throw new Error("Invalid state");
37808         },
37809         enumerable: true,
37810         configurable: true
37811     });
37812     Object.defineProperty(StateContext.prototype, "reference", {
37813         get: function () {
37814             return this._state.reference;
37815         },
37816         enumerable: true,
37817         configurable: true
37818     });
37819     Object.defineProperty(StateContext.prototype, "alpha", {
37820         get: function () {
37821             return this._state.alpha;
37822         },
37823         enumerable: true,
37824         configurable: true
37825     });
37826     Object.defineProperty(StateContext.prototype, "camera", {
37827         get: function () {
37828             return this._state.camera;
37829         },
37830         enumerable: true,
37831         configurable: true
37832     });
37833     Object.defineProperty(StateContext.prototype, "zoom", {
37834         get: function () {
37835             return this._state.zoom;
37836         },
37837         enumerable: true,
37838         configurable: true
37839     });
37840     Object.defineProperty(StateContext.prototype, "currentNode", {
37841         get: function () {
37842             return this._state.currentNode;
37843         },
37844         enumerable: true,
37845         configurable: true
37846     });
37847     Object.defineProperty(StateContext.prototype, "previousNode", {
37848         get: function () {
37849             return this._state.previousNode;
37850         },
37851         enumerable: true,
37852         configurable: true
37853     });
37854     Object.defineProperty(StateContext.prototype, "currentCamera", {
37855         get: function () {
37856             return this._state.currentCamera;
37857         },
37858         enumerable: true,
37859         configurable: true
37860     });
37861     Object.defineProperty(StateContext.prototype, "currentTransform", {
37862         get: function () {
37863             return this._state.currentTransform;
37864         },
37865         enumerable: true,
37866         configurable: true
37867     });
37868     Object.defineProperty(StateContext.prototype, "previousTransform", {
37869         get: function () {
37870             return this._state.previousTransform;
37871         },
37872         enumerable: true,
37873         configurable: true
37874     });
37875     Object.defineProperty(StateContext.prototype, "trajectory", {
37876         get: function () {
37877             return this._state.trajectory;
37878         },
37879         enumerable: true,
37880         configurable: true
37881     });
37882     Object.defineProperty(StateContext.prototype, "currentIndex", {
37883         get: function () {
37884             return this._state.currentIndex;
37885         },
37886         enumerable: true,
37887         configurable: true
37888     });
37889     Object.defineProperty(StateContext.prototype, "lastNode", {
37890         get: function () {
37891             return this._state.trajectory[this._state.trajectory.length - 1];
37892         },
37893         enumerable: true,
37894         configurable: true
37895     });
37896     Object.defineProperty(StateContext.prototype, "nodesAhead", {
37897         get: function () {
37898             return this._state.trajectory.length - 1 - this._state.currentIndex;
37899         },
37900         enumerable: true,
37901         configurable: true
37902     });
37903     Object.defineProperty(StateContext.prototype, "motionless", {
37904         get: function () {
37905             return this._state.motionless;
37906         },
37907         enumerable: true,
37908         configurable: true
37909     });
37910     StateContext.prototype.getCenter = function () {
37911         return this._state.getCenter();
37912     };
37913     StateContext.prototype.setCenter = function (center) {
37914         this._state.setCenter(center);
37915     };
37916     StateContext.prototype.setZoom = function (zoom) {
37917         this._state.setZoom(zoom);
37918     };
37919     StateContext.prototype.update = function (fps) {
37920         this._state.update(fps);
37921     };
37922     StateContext.prototype.append = function (nodes) {
37923         this._state.append(nodes);
37924     };
37925     StateContext.prototype.prepend = function (nodes) {
37926         this._state.prepend(nodes);
37927     };
37928     StateContext.prototype.remove = function (n) {
37929         this._state.remove(n);
37930     };
37931     StateContext.prototype.clear = function () {
37932         this._state.clear();
37933     };
37934     StateContext.prototype.clearPrior = function () {
37935         this._state.clearPrior();
37936     };
37937     StateContext.prototype.cut = function () {
37938         this._state.cut();
37939     };
37940     StateContext.prototype.set = function (nodes) {
37941         this._state.set(nodes);
37942     };
37943     StateContext.prototype.rotate = function (delta) {
37944         this._state.rotate(delta);
37945     };
37946     StateContext.prototype.rotateBasic = function (basicRotation) {
37947         this._state.rotateBasic(basicRotation);
37948     };
37949     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
37950         this._state.rotateBasicUnbounded(basicRotation);
37951     };
37952     StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
37953         this._state.rotateBasicWithoutInertia(basicRotation);
37954     };
37955     StateContext.prototype.rotateToBasic = function (basic) {
37956         this._state.rotateToBasic(basic);
37957     };
37958     StateContext.prototype.move = function (delta) {
37959         this._state.move(delta);
37960     };
37961     StateContext.prototype.moveTo = function (delta) {
37962         this._state.moveTo(delta);
37963     };
37964     StateContext.prototype.zoomIn = function (delta, reference) {
37965         this._state.zoomIn(delta, reference);
37966     };
37967     return StateContext;
37968 }());
37969 exports.StateContext = StateContext;
37970
37971 },{"../Geo":233,"../State":237}],351:[function(require,module,exports){
37972 "use strict";
37973 Object.defineProperty(exports, "__esModule", { value: true });
37974 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37975 var Subject_1 = require("rxjs/Subject");
37976 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
37977 require("rxjs/add/operator/bufferCount");
37978 require("rxjs/add/operator/distinctUntilChanged");
37979 require("rxjs/add/operator/do");
37980 require("rxjs/add/operator/filter");
37981 require("rxjs/add/operator/first");
37982 require("rxjs/add/operator/map");
37983 require("rxjs/add/operator/pairwise");
37984 require("rxjs/add/operator/publishReplay");
37985 require("rxjs/add/operator/scan");
37986 require("rxjs/add/operator/startWith");
37987 require("rxjs/add/operator/switchMap");
37988 require("rxjs/add/operator/withLatestFrom");
37989 var State_1 = require("../State");
37990 var StateService = (function () {
37991     function StateService() {
37992         var _this = this;
37993         this._appendNode$ = new Subject_1.Subject();
37994         this._start$ = new Subject_1.Subject();
37995         this._frame$ = new Subject_1.Subject();
37996         this._fpsSampleRate = 30;
37997         this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
37998             return context;
37999         });
38000         this._context$ = this._contextOperation$
38001             .scan(function (context, operation) {
38002             return operation(context);
38003         }, new State_1.StateContext())
38004             .publishReplay(1)
38005             .refCount();
38006         this._state$ = this._context$
38007             .map(function (context) {
38008             return context.state;
38009         })
38010             .distinctUntilChanged()
38011             .publishReplay(1)
38012             .refCount();
38013         this._fps$ = this._start$
38014             .switchMap(function () {
38015             return _this._frame$
38016                 .bufferCount(1, _this._fpsSampleRate)
38017                 .map(function (frameIds) {
38018                 return new Date().getTime();
38019             })
38020                 .pairwise()
38021                 .map(function (times) {
38022                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
38023             })
38024                 .startWith(60);
38025         })
38026             .share();
38027         this._currentState$ = this._frame$
38028             .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
38029             return [frameId, fps, context];
38030         })
38031             .filter(function (fc) {
38032             return fc[2].currentNode != null;
38033         })
38034             .do(function (fc) {
38035             fc[2].update(fc[1]);
38036         })
38037             .map(function (fc) {
38038             return { fps: fc[1], id: fc[0], state: fc[2] };
38039         })
38040             .share();
38041         this._lastState$ = this._currentState$
38042             .publishReplay(1)
38043             .refCount();
38044         var nodeChanged$ = this._currentState$
38045             .distinctUntilChanged(undefined, function (f) {
38046             return f.state.currentNode.key;
38047         })
38048             .publishReplay(1)
38049             .refCount();
38050         var nodeChangedSubject$ = new Subject_1.Subject();
38051         nodeChanged$
38052             .subscribe(nodeChangedSubject$);
38053         this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
38054         nodeChangedSubject$
38055             .map(function (f) {
38056             return f.state.currentNode.key;
38057         })
38058             .subscribe(this._currentKey$);
38059         this._currentNode$ = nodeChangedSubject$
38060             .map(function (f) {
38061             return f.state.currentNode;
38062         })
38063             .publishReplay(1)
38064             .refCount();
38065         this._currentCamera$ = nodeChangedSubject$
38066             .map(function (f) {
38067             return f.state.currentCamera;
38068         })
38069             .publishReplay(1)
38070             .refCount();
38071         this._currentTransform$ = nodeChangedSubject$
38072             .map(function (f) {
38073             return f.state.currentTransform;
38074         })
38075             .publishReplay(1)
38076             .refCount();
38077         this._reference$ = nodeChangedSubject$
38078             .map(function (f) {
38079             return f.state.reference;
38080         })
38081             .distinctUntilChanged(function (r1, r2) {
38082             return r1.lat === r2.lat && r1.lon === r2.lon;
38083         }, function (reference) {
38084             return { lat: reference.lat, lon: reference.lon };
38085         })
38086             .publishReplay(1)
38087             .refCount();
38088         this._currentNodeExternal$ = nodeChanged$
38089             .map(function (f) {
38090             return f.state.currentNode;
38091         })
38092             .publishReplay(1)
38093             .refCount();
38094         this._appendNode$
38095             .map(function (node) {
38096             return function (context) {
38097                 context.append([node]);
38098                 return context;
38099             };
38100         })
38101             .subscribe(this._contextOperation$);
38102         this._inMotionOperation$ = new Subject_1.Subject();
38103         nodeChanged$
38104             .map(function (frame) {
38105             return true;
38106         })
38107             .subscribe(this._inMotionOperation$);
38108         this._inMotionOperation$
38109             .distinctUntilChanged()
38110             .filter(function (moving) {
38111             return moving;
38112         })
38113             .switchMap(function (moving) {
38114             return _this._currentState$
38115                 .filter(function (frame) {
38116                 return frame.state.nodesAhead === 0;
38117             })
38118                 .map(function (frame) {
38119                 return [frame.state.camera.clone(), frame.state.zoom];
38120             })
38121                 .pairwise()
38122                 .map(function (pair) {
38123                 var c1 = pair[0][0];
38124                 var c2 = pair[1][0];
38125                 var z1 = pair[0][1];
38126                 var z2 = pair[1][1];
38127                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
38128             })
38129                 .first(function (changed) {
38130                 return !changed;
38131             });
38132         })
38133             .subscribe(this._inMotionOperation$);
38134         this._inMotion$ = this._inMotionOperation$
38135             .distinctUntilChanged()
38136             .publishReplay(1)
38137             .refCount();
38138         this._inTranslationOperation$ = new Subject_1.Subject();
38139         nodeChanged$
38140             .map(function (frame) {
38141             return true;
38142         })
38143             .subscribe(this._inTranslationOperation$);
38144         this._inTranslationOperation$
38145             .distinctUntilChanged()
38146             .filter(function (inTranslation) {
38147             return inTranslation;
38148         })
38149             .switchMap(function (inTranslation) {
38150             return _this._currentState$
38151                 .filter(function (frame) {
38152                 return frame.state.nodesAhead === 0;
38153             })
38154                 .map(function (frame) {
38155                 return frame.state.camera.position.clone();
38156             })
38157                 .pairwise()
38158                 .map(function (pair) {
38159                 return pair[0].distanceToSquared(pair[1]) !== 0;
38160             })
38161                 .first(function (changed) {
38162                 return !changed;
38163             });
38164         })
38165             .subscribe(this._inTranslationOperation$);
38166         this._inTranslation$ = this._inTranslationOperation$
38167             .distinctUntilChanged()
38168             .publishReplay(1)
38169             .refCount();
38170         this._state$.subscribe(function () { });
38171         this._currentNode$.subscribe(function () { });
38172         this._currentCamera$.subscribe(function () { });
38173         this._currentTransform$.subscribe(function () { });
38174         this._reference$.subscribe(function () { });
38175         this._currentNodeExternal$.subscribe(function () { });
38176         this._lastState$.subscribe(function () { });
38177         this._inMotion$.subscribe(function () { });
38178         this._inTranslation$.subscribe(function () { });
38179         this._frameId = null;
38180         this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
38181     }
38182     Object.defineProperty(StateService.prototype, "currentState$", {
38183         get: function () {
38184             return this._currentState$;
38185         },
38186         enumerable: true,
38187         configurable: true
38188     });
38189     Object.defineProperty(StateService.prototype, "currentNode$", {
38190         get: function () {
38191             return this._currentNode$;
38192         },
38193         enumerable: true,
38194         configurable: true
38195     });
38196     Object.defineProperty(StateService.prototype, "currentKey$", {
38197         get: function () {
38198             return this._currentKey$;
38199         },
38200         enumerable: true,
38201         configurable: true
38202     });
38203     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
38204         get: function () {
38205             return this._currentNodeExternal$;
38206         },
38207         enumerable: true,
38208         configurable: true
38209     });
38210     Object.defineProperty(StateService.prototype, "currentCamera$", {
38211         get: function () {
38212             return this._currentCamera$;
38213         },
38214         enumerable: true,
38215         configurable: true
38216     });
38217     Object.defineProperty(StateService.prototype, "currentTransform$", {
38218         get: function () {
38219             return this._currentTransform$;
38220         },
38221         enumerable: true,
38222         configurable: true
38223     });
38224     Object.defineProperty(StateService.prototype, "state$", {
38225         get: function () {
38226             return this._state$;
38227         },
38228         enumerable: true,
38229         configurable: true
38230     });
38231     Object.defineProperty(StateService.prototype, "reference$", {
38232         get: function () {
38233             return this._reference$;
38234         },
38235         enumerable: true,
38236         configurable: true
38237     });
38238     Object.defineProperty(StateService.prototype, "inMotion$", {
38239         get: function () {
38240             return this._inMotion$;
38241         },
38242         enumerable: true,
38243         configurable: true
38244     });
38245     Object.defineProperty(StateService.prototype, "inTranslation$", {
38246         get: function () {
38247             return this._inTranslation$;
38248         },
38249         enumerable: true,
38250         configurable: true
38251     });
38252     Object.defineProperty(StateService.prototype, "appendNode$", {
38253         get: function () {
38254             return this._appendNode$;
38255         },
38256         enumerable: true,
38257         configurable: true
38258     });
38259     StateService.prototype.traverse = function () {
38260         this._inMotionOperation$.next(true);
38261         this._invokeContextOperation(function (context) { context.traverse(); });
38262     };
38263     StateService.prototype.wait = function () {
38264         this._invokeContextOperation(function (context) { context.wait(); });
38265     };
38266     StateService.prototype.appendNodes = function (nodes) {
38267         this._invokeContextOperation(function (context) { context.append(nodes); });
38268     };
38269     StateService.prototype.prependNodes = function (nodes) {
38270         this._invokeContextOperation(function (context) { context.prepend(nodes); });
38271     };
38272     StateService.prototype.removeNodes = function (n) {
38273         this._invokeContextOperation(function (context) { context.remove(n); });
38274     };
38275     StateService.prototype.clearNodes = function () {
38276         this._invokeContextOperation(function (context) { context.clear(); });
38277     };
38278     StateService.prototype.clearPriorNodes = function () {
38279         this._invokeContextOperation(function (context) { context.clearPrior(); });
38280     };
38281     StateService.prototype.cutNodes = function () {
38282         this._invokeContextOperation(function (context) { context.cut(); });
38283     };
38284     StateService.prototype.setNodes = function (nodes) {
38285         this._invokeContextOperation(function (context) { context.set(nodes); });
38286     };
38287     StateService.prototype.rotate = function (delta) {
38288         this._inMotionOperation$.next(true);
38289         this._invokeContextOperation(function (context) { context.rotate(delta); });
38290     };
38291     StateService.prototype.rotateBasic = function (basicRotation) {
38292         this._inMotionOperation$.next(true);
38293         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
38294     };
38295     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
38296         this._inMotionOperation$.next(true);
38297         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
38298     };
38299     StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
38300         this._inMotionOperation$.next(true);
38301         this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
38302     };
38303     StateService.prototype.rotateToBasic = function (basic) {
38304         this._inMotionOperation$.next(true);
38305         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
38306     };
38307     StateService.prototype.move = function (delta) {
38308         this._inMotionOperation$.next(true);
38309         this._invokeContextOperation(function (context) { context.move(delta); });
38310     };
38311     StateService.prototype.moveTo = function (position) {
38312         this._inMotionOperation$.next(true);
38313         this._invokeContextOperation(function (context) { context.moveTo(position); });
38314     };
38315     /**
38316      * Change zoom level while keeping the reference point position approximately static.
38317      *
38318      * @parameter {number} delta - Change in zoom level.
38319      * @parameter {Array<number>} reference - Reference point in basic coordinates.
38320      */
38321     StateService.prototype.zoomIn = function (delta, reference) {
38322         this._inMotionOperation$.next(true);
38323         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
38324     };
38325     StateService.prototype.getCenter = function () {
38326         return this._lastState$
38327             .first()
38328             .map(function (frame) {
38329             return frame.state.getCenter();
38330         });
38331     };
38332     StateService.prototype.getZoom = function () {
38333         return this._lastState$
38334             .first()
38335             .map(function (frame) {
38336             return frame.state.zoom;
38337         });
38338     };
38339     StateService.prototype.setCenter = function (center) {
38340         this._inMotionOperation$.next(true);
38341         this._invokeContextOperation(function (context) { context.setCenter(center); });
38342     };
38343     StateService.prototype.setZoom = function (zoom) {
38344         this._inMotionOperation$.next(true);
38345         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
38346     };
38347     StateService.prototype.start = function () {
38348         if (this._frameId == null) {
38349             this._start$.next(null);
38350             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
38351             this._frame$.next(this._frameId);
38352         }
38353     };
38354     StateService.prototype.stop = function () {
38355         if (this._frameId != null) {
38356             this._frameGenerator.cancelAnimationFrame(this._frameId);
38357             this._frameId = null;
38358         }
38359     };
38360     StateService.prototype._invokeContextOperation = function (action) {
38361         this._contextOperation$
38362             .next(function (context) {
38363             action(context);
38364             return context;
38365         });
38366     };
38367     StateService.prototype._frame = function (time) {
38368         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
38369         this._frame$.next(this._frameId);
38370     };
38371     return StateService;
38372 }());
38373 exports.StateService = StateService;
38374
38375 },{"../State":237,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/startWith":79,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/withLatestFrom":85,"rxjs/util/AnimationFrame":161}],352:[function(require,module,exports){
38376 "use strict";
38377 /// <reference path="../../../typings/index.d.ts" />
38378 Object.defineProperty(exports, "__esModule", { value: true });
38379 var Error_1 = require("../../Error");
38380 var Geo_1 = require("../../Geo");
38381 var StateBase = (function () {
38382     function StateBase(state) {
38383         this._spatial = new Geo_1.Spatial();
38384         this._geoCoords = new Geo_1.GeoCoords();
38385         this._referenceThreshold = 0.01;
38386         this._reference = state.reference;
38387         this._alpha = state.alpha;
38388         this._camera = state.camera.clone();
38389         this._zoom = state.zoom;
38390         this._currentIndex = state.currentIndex;
38391         this._trajectory = state.trajectory.slice();
38392         this._trajectoryTransforms = [];
38393         this._trajectoryCameras = [];
38394         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
38395             var node = _a[_i];
38396             var translation = this._nodeToTranslation(node);
38397             var transform = new Geo_1.Transform(node, node.image, translation);
38398             this._trajectoryTransforms.push(transform);
38399             this._trajectoryCameras.push(new Geo_1.Camera(transform));
38400         }
38401         this._currentNode = this._trajectory.length > 0 ?
38402             this._trajectory[this._currentIndex] :
38403             null;
38404         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
38405             this._trajectory[this._currentIndex - 1] :
38406             null;
38407         this._currentCamera = this._trajectoryCameras.length > 0 ?
38408             this._trajectoryCameras[this._currentIndex].clone() :
38409             new Geo_1.Camera();
38410         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
38411             this._trajectoryCameras[this._currentIndex - 1].clone() :
38412             this._currentCamera.clone();
38413     }
38414     Object.defineProperty(StateBase.prototype, "reference", {
38415         get: function () {
38416             return this._reference;
38417         },
38418         enumerable: true,
38419         configurable: true
38420     });
38421     Object.defineProperty(StateBase.prototype, "alpha", {
38422         get: function () {
38423             return this._getAlpha();
38424         },
38425         enumerable: true,
38426         configurable: true
38427     });
38428     Object.defineProperty(StateBase.prototype, "camera", {
38429         get: function () {
38430             return this._camera;
38431         },
38432         enumerable: true,
38433         configurable: true
38434     });
38435     Object.defineProperty(StateBase.prototype, "zoom", {
38436         get: function () {
38437             return this._zoom;
38438         },
38439         enumerable: true,
38440         configurable: true
38441     });
38442     Object.defineProperty(StateBase.prototype, "trajectory", {
38443         get: function () {
38444             return this._trajectory;
38445         },
38446         enumerable: true,
38447         configurable: true
38448     });
38449     Object.defineProperty(StateBase.prototype, "currentIndex", {
38450         get: function () {
38451             return this._currentIndex;
38452         },
38453         enumerable: true,
38454         configurable: true
38455     });
38456     Object.defineProperty(StateBase.prototype, "currentNode", {
38457         get: function () {
38458             return this._currentNode;
38459         },
38460         enumerable: true,
38461         configurable: true
38462     });
38463     Object.defineProperty(StateBase.prototype, "previousNode", {
38464         get: function () {
38465             return this._previousNode;
38466         },
38467         enumerable: true,
38468         configurable: true
38469     });
38470     Object.defineProperty(StateBase.prototype, "currentCamera", {
38471         get: function () {
38472             return this._currentCamera;
38473         },
38474         enumerable: true,
38475         configurable: true
38476     });
38477     Object.defineProperty(StateBase.prototype, "currentTransform", {
38478         get: function () {
38479             return this._trajectoryTransforms.length > 0 ?
38480                 this._trajectoryTransforms[this.currentIndex] : null;
38481         },
38482         enumerable: true,
38483         configurable: true
38484     });
38485     Object.defineProperty(StateBase.prototype, "previousTransform", {
38486         get: function () {
38487             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
38488                 this._trajectoryTransforms[this.currentIndex - 1] : null;
38489         },
38490         enumerable: true,
38491         configurable: true
38492     });
38493     Object.defineProperty(StateBase.prototype, "motionless", {
38494         get: function () {
38495             return this._motionless;
38496         },
38497         enumerable: true,
38498         configurable: true
38499     });
38500     StateBase.prototype.append = function (nodes) {
38501         if (nodes.length < 1) {
38502             throw Error("Trajectory can not be empty");
38503         }
38504         if (this._currentIndex < 0) {
38505             this.set(nodes);
38506         }
38507         else {
38508             this._trajectory = this._trajectory.concat(nodes);
38509             this._appendToTrajectories(nodes);
38510         }
38511     };
38512     StateBase.prototype.prepend = function (nodes) {
38513         if (nodes.length < 1) {
38514             throw Error("Trajectory can not be empty");
38515         }
38516         this._trajectory = nodes.slice().concat(this._trajectory);
38517         this._currentIndex += nodes.length;
38518         this._setCurrentNode();
38519         var referenceReset = this._setReference(this._currentNode);
38520         if (referenceReset) {
38521             this._setTrajectories();
38522         }
38523         else {
38524             this._prependToTrajectories(nodes);
38525         }
38526         this._setCurrentCamera();
38527     };
38528     StateBase.prototype.remove = function (n) {
38529         if (n < 0) {
38530             throw Error("n must be a positive integer");
38531         }
38532         if (this._currentIndex - 1 < n) {
38533             throw Error("Current and previous nodes can not be removed");
38534         }
38535         for (var i = 0; i < n; i++) {
38536             this._trajectory.shift();
38537             this._trajectoryTransforms.shift();
38538             this._trajectoryCameras.shift();
38539             this._currentIndex--;
38540         }
38541         this._setCurrentNode();
38542     };
38543     StateBase.prototype.clearPrior = function () {
38544         if (this._currentIndex > 0) {
38545             this.remove(this._currentIndex - 1);
38546         }
38547     };
38548     StateBase.prototype.clear = function () {
38549         this.cut();
38550         if (this._currentIndex > 0) {
38551             this.remove(this._currentIndex - 1);
38552         }
38553     };
38554     StateBase.prototype.cut = function () {
38555         while (this._trajectory.length - 1 > this._currentIndex) {
38556             this._trajectory.pop();
38557             this._trajectoryTransforms.pop();
38558             this._trajectoryCameras.pop();
38559         }
38560     };
38561     StateBase.prototype.set = function (nodes) {
38562         this._setTrajectory(nodes);
38563         this._setCurrentNode();
38564         this._setReference(this._currentNode);
38565         this._setTrajectories();
38566         this._setCurrentCamera();
38567     };
38568     StateBase.prototype.getCenter = function () {
38569         return this._currentNode != null ?
38570             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
38571             [0.5, 0.5];
38572     };
38573     StateBase.prototype._setCurrent = function () {
38574         this._setCurrentNode();
38575         var referenceReset = this._setReference(this._currentNode);
38576         if (referenceReset) {
38577             this._setTrajectories();
38578         }
38579         this._setCurrentCamera();
38580     };
38581     StateBase.prototype._setCurrentCamera = function () {
38582         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
38583         this._previousCamera = this._currentIndex > 0 ?
38584             this._trajectoryCameras[this._currentIndex - 1].clone() :
38585             this._currentCamera.clone();
38586     };
38587     StateBase.prototype._motionlessTransition = function () {
38588         var nodesSet = this._currentNode != null && this._previousNode != null;
38589         return nodesSet && !(this._currentNode.merged &&
38590             this._previousNode.merged &&
38591             this._withinOriginalDistance() &&
38592             this._sameConnectedComponent());
38593     };
38594     StateBase.prototype._setReference = function (node) {
38595         // do not reset reference if node is within threshold distance
38596         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
38597             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
38598             return false;
38599         }
38600         // do not reset reference if previous node exist and transition is with motion
38601         if (this._previousNode != null && !this._motionlessTransition()) {
38602             return false;
38603         }
38604         this._reference.lat = node.latLon.lat;
38605         this._reference.lon = node.latLon.lon;
38606         this._reference.alt = node.alt;
38607         return true;
38608     };
38609     StateBase.prototype._setCurrentNode = function () {
38610         this._currentNode = this._trajectory.length > 0 ?
38611             this._trajectory[this._currentIndex] :
38612             null;
38613         this._previousNode = this._currentIndex > 0 ?
38614             this._trajectory[this._currentIndex - 1] :
38615             null;
38616     };
38617     StateBase.prototype._setTrajectory = function (nodes) {
38618         if (nodes.length < 1) {
38619             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
38620         }
38621         if (this._currentNode != null) {
38622             this._trajectory = [this._currentNode].concat(nodes);
38623             this._currentIndex = 1;
38624         }
38625         else {
38626             this._trajectory = nodes.slice();
38627             this._currentIndex = 0;
38628         }
38629     };
38630     StateBase.prototype._setTrajectories = function () {
38631         this._trajectoryTransforms.length = 0;
38632         this._trajectoryCameras.length = 0;
38633         this._appendToTrajectories(this._trajectory);
38634     };
38635     StateBase.prototype._appendToTrajectories = function (nodes) {
38636         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
38637             var node = nodes_1[_i];
38638             if (!node.assetsCached) {
38639                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
38640             }
38641             var translation = this._nodeToTranslation(node);
38642             var transform = new Geo_1.Transform(node, node.image, translation);
38643             this._trajectoryTransforms.push(transform);
38644             this._trajectoryCameras.push(new Geo_1.Camera(transform));
38645         }
38646     };
38647     StateBase.prototype._prependToTrajectories = function (nodes) {
38648         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
38649             var node = _a[_i];
38650             if (!node.assetsCached) {
38651                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
38652             }
38653             var translation = this._nodeToTranslation(node);
38654             var transform = new Geo_1.Transform(node, node.image, translation);
38655             this._trajectoryTransforms.unshift(transform);
38656             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
38657         }
38658     };
38659     StateBase.prototype._nodeToTranslation = function (node) {
38660         var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
38661         var RC = this._spatial.rotate(C, node.rotation);
38662         return [-RC.x, -RC.y, -RC.z];
38663     };
38664     StateBase.prototype._sameConnectedComponent = function () {
38665         var current = this._currentNode;
38666         var previous = this._previousNode;
38667         if (!current ||
38668             !current.mergeCC ||
38669             !previous ||
38670             !previous.mergeCC) {
38671             return true;
38672         }
38673         return current.mergeCC === previous.mergeCC;
38674     };
38675     StateBase.prototype._withinOriginalDistance = function () {
38676         var current = this._currentNode;
38677         var previous = this._previousNode;
38678         if (!current || !previous) {
38679             return true;
38680         }
38681         // 50 km/h moves 28m in 2s
38682         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
38683         return distance < 25;
38684     };
38685     return StateBase;
38686 }());
38687 exports.StateBase = StateBase;
38688
38689 },{"../../Error":232,"../../Geo":233}],353:[function(require,module,exports){
38690 "use strict";
38691 /// <reference path="../../../typings/index.d.ts" />
38692 var __extends = (this && this.__extends) || (function () {
38693     var extendStatics = Object.setPrototypeOf ||
38694         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
38695         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
38696     return function (d, b) {
38697         extendStatics(d, b);
38698         function __() { this.constructor = d; }
38699         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38700     };
38701 })();
38702 Object.defineProperty(exports, "__esModule", { value: true });
38703 var THREE = require("three");
38704 var UnitBezier = require("@mapbox/unitbezier");
38705 var State_1 = require("../../State");
38706 var RotationDelta = (function () {
38707     function RotationDelta(phi, theta) {
38708         this._phi = phi;
38709         this._theta = theta;
38710     }
38711     Object.defineProperty(RotationDelta.prototype, "phi", {
38712         get: function () {
38713             return this._phi;
38714         },
38715         set: function (value) {
38716             this._phi = value;
38717         },
38718         enumerable: true,
38719         configurable: true
38720     });
38721     Object.defineProperty(RotationDelta.prototype, "theta", {
38722         get: function () {
38723             return this._theta;
38724         },
38725         set: function (value) {
38726             this._theta = value;
38727         },
38728         enumerable: true,
38729         configurable: true
38730     });
38731     Object.defineProperty(RotationDelta.prototype, "isZero", {
38732         get: function () {
38733             return this._phi === 0 && this._theta === 0;
38734         },
38735         enumerable: true,
38736         configurable: true
38737     });
38738     RotationDelta.prototype.copy = function (delta) {
38739         this._phi = delta.phi;
38740         this._theta = delta.theta;
38741     };
38742     RotationDelta.prototype.lerp = function (other, alpha) {
38743         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
38744         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
38745     };
38746     RotationDelta.prototype.multiply = function (value) {
38747         this._phi *= value;
38748         this._theta *= value;
38749     };
38750     RotationDelta.prototype.threshold = function (value) {
38751         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
38752         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
38753     };
38754     RotationDelta.prototype.lengthSquared = function () {
38755         return this._phi * this._phi + this._theta * this._theta;
38756     };
38757     RotationDelta.prototype.reset = function () {
38758         this._phi = 0;
38759         this._theta = 0;
38760     };
38761     return RotationDelta;
38762 }());
38763 var TraversingState = (function (_super) {
38764     __extends(TraversingState, _super);
38765     function TraversingState(state) {
38766         var _this = _super.call(this, state) || this;
38767         _this._adjustCameras();
38768         _this._motionless = _this._motionlessTransition();
38769         _this._baseAlpha = _this._alpha;
38770         _this._animationSpeed = 0.025;
38771         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
38772         _this._useBezier = false;
38773         _this._rotationDelta = new RotationDelta(0, 0);
38774         _this._requestedRotationDelta = null;
38775         _this._basicRotation = [0, 0];
38776         _this._requestedBasicRotation = null;
38777         _this._requestedBasicRotationUnbounded = null;
38778         _this._rotationAcceleration = 0.86;
38779         _this._rotationIncreaseAlpha = 0.97;
38780         _this._rotationDecreaseAlpha = 0.9;
38781         _this._rotationThreshold = 1e-3;
38782         _this._unboundedRotationAlpha = 0.8;
38783         _this._desiredZoom = state.zoom;
38784         _this._minZoom = 0;
38785         _this._maxZoom = 3;
38786         _this._lookatDepth = 10;
38787         _this._desiredLookat = null;
38788         _this._desiredCenter = null;
38789         return _this;
38790     }
38791     TraversingState.prototype.traverse = function () {
38792         throw new Error("Not implemented");
38793     };
38794     TraversingState.prototype.wait = function () {
38795         return new State_1.WaitingState(this);
38796     };
38797     TraversingState.prototype.append = function (nodes) {
38798         var emptyTrajectory = this._trajectory.length === 0;
38799         if (emptyTrajectory) {
38800             this._resetTransition();
38801         }
38802         _super.prototype.append.call(this, nodes);
38803         if (emptyTrajectory) {
38804             this._setDesiredCenter();
38805             this._setDesiredZoom();
38806         }
38807     };
38808     TraversingState.prototype.prepend = function (nodes) {
38809         var emptyTrajectory = this._trajectory.length === 0;
38810         if (emptyTrajectory) {
38811             this._resetTransition();
38812         }
38813         _super.prototype.prepend.call(this, nodes);
38814         if (emptyTrajectory) {
38815             this._setDesiredCenter();
38816             this._setDesiredZoom();
38817         }
38818     };
38819     TraversingState.prototype.set = function (nodes) {
38820         _super.prototype.set.call(this, nodes);
38821         this._desiredLookat = null;
38822         this._resetTransition();
38823         this._clearRotation();
38824         this._setDesiredCenter();
38825         this._setDesiredZoom();
38826         if (this._trajectory.length < 3) {
38827             this._useBezier = true;
38828         }
38829     };
38830     TraversingState.prototype.move = function (delta) {
38831         throw new Error("Not implemented");
38832     };
38833     TraversingState.prototype.moveTo = function (delta) {
38834         throw new Error("Not implemented");
38835     };
38836     TraversingState.prototype.rotate = function (rotationDelta) {
38837         if (this._currentNode == null) {
38838             return;
38839         }
38840         this._desiredZoom = this._zoom;
38841         this._desiredLookat = null;
38842         this._requestedBasicRotation = null;
38843         if (this._requestedRotationDelta != null) {
38844             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
38845             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
38846         }
38847         else {
38848             this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
38849         }
38850     };
38851     TraversingState.prototype.rotateBasic = function (basicRotation) {
38852         if (this._currentNode == null) {
38853             return;
38854         }
38855         this._desiredZoom = this._zoom;
38856         this._desiredLookat = null;
38857         this._requestedRotationDelta = null;
38858         if (this._requestedBasicRotation != null) {
38859             this._requestedBasicRotation[0] += basicRotation[0];
38860             this._requestedBasicRotation[1] += basicRotation[1];
38861             var threshold = 0.05 / Math.pow(2, this._zoom);
38862             this._requestedBasicRotation[0] =
38863                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
38864             this._requestedBasicRotation[1] =
38865                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
38866         }
38867         else {
38868             this._requestedBasicRotation = basicRotation.slice();
38869         }
38870     };
38871     TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
38872         if (this._currentNode == null) {
38873             return;
38874         }
38875         if (this._requestedBasicRotationUnbounded != null) {
38876             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
38877             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
38878         }
38879         else {
38880             this._requestedBasicRotationUnbounded = basicRotation.slice();
38881         }
38882     };
38883     TraversingState.prototype.rotateBasicWithoutInertia = function (basic) {
38884         if (this._currentNode == null) {
38885             return;
38886         }
38887         this._desiredZoom = this._zoom;
38888         this._desiredLookat = null;
38889         this._requestedRotationDelta = null;
38890         this._requestedBasicRotation = null;
38891         var threshold = 0.05 / Math.pow(2, this._zoom);
38892         var basicRotation = basic.slice();
38893         basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
38894         basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
38895         this._applyRotationBasic(basicRotation);
38896     };
38897     TraversingState.prototype.rotateToBasic = function (basic) {
38898         if (this._currentNode == null) {
38899             return;
38900         }
38901         this._desiredZoom = this._zoom;
38902         this._desiredLookat = null;
38903         basic[0] = this._spatial.clamp(basic[0], 0, 1);
38904         basic[1] = this._spatial.clamp(basic[1], 0, 1);
38905         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
38906         this._currentCamera.lookat.fromArray(lookat);
38907     };
38908     TraversingState.prototype.zoomIn = function (delta, reference) {
38909         if (this._currentNode == null) {
38910             return;
38911         }
38912         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
38913         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
38914         var currentCenterX = currentCenter[0];
38915         var currentCenterY = currentCenter[1];
38916         var zoom0 = Math.pow(2, this._zoom);
38917         var zoom1 = Math.pow(2, this._desiredZoom);
38918         var refX = reference[0];
38919         var refY = reference[1];
38920         if (this.currentTransform.gpano != null &&
38921             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
38922             if (refX - currentCenterX > 0.5) {
38923                 refX = refX - 1;
38924             }
38925             else if (currentCenterX - refX > 0.5) {
38926                 refX = 1 + refX;
38927             }
38928         }
38929         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
38930         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
38931         var gpano = this.currentTransform.gpano;
38932         if (this._currentNode.fullPano) {
38933             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
38934             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
38935         }
38936         else if (gpano != null &&
38937             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
38938             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
38939             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
38940         }
38941         else {
38942             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
38943             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
38944         }
38945         this._desiredLookat = new THREE.Vector3()
38946             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
38947     };
38948     TraversingState.prototype.setCenter = function (center) {
38949         this._desiredLookat = null;
38950         this._requestedRotationDelta = null;
38951         this._requestedBasicRotation = null;
38952         this._desiredZoom = this._zoom;
38953         var clamped = [
38954             this._spatial.clamp(center[0], 0, 1),
38955             this._spatial.clamp(center[1], 0, 1),
38956         ];
38957         if (this._currentNode == null) {
38958             this._desiredCenter = clamped;
38959             return;
38960         }
38961         this._desiredCenter = null;
38962         var currentLookat = new THREE.Vector3()
38963             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
38964         var previousTransform = this.previousTransform != null ?
38965             this.previousTransform :
38966             this.currentTransform;
38967         var previousLookat = new THREE.Vector3()
38968             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
38969         this._currentCamera.lookat.copy(currentLookat);
38970         this._previousCamera.lookat.copy(previousLookat);
38971     };
38972     TraversingState.prototype.setZoom = function (zoom) {
38973         this._desiredLookat = null;
38974         this._requestedRotationDelta = null;
38975         this._requestedBasicRotation = null;
38976         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
38977         this._desiredZoom = this._zoom;
38978     };
38979     TraversingState.prototype.update = function (fps) {
38980         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
38981             this._currentIndex += 1;
38982             this._useBezier = this._trajectory.length < 3 &&
38983                 this._currentIndex + 1 === this._trajectory.length;
38984             this._setCurrent();
38985             this._resetTransition();
38986             this._clearRotation();
38987             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
38988             this._desiredLookat = null;
38989         }
38990         var animationSpeed = this._animationSpeed * (60 / fps);
38991         this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
38992         if (this._useBezier) {
38993             this._alpha = this._unitBezier.solve(this._baseAlpha);
38994         }
38995         else {
38996             this._alpha = this._baseAlpha;
38997         }
38998         this._updateRotation();
38999         if (!this._rotationDelta.isZero) {
39000             this._applyRotation(this._previousCamera);
39001             this._applyRotation(this._currentCamera);
39002         }
39003         this._updateRotationBasic();
39004         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
39005             this._applyRotationBasic(this._basicRotation);
39006         }
39007         this._updateZoom(animationSpeed);
39008         this._updateLookat(animationSpeed);
39009         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
39010     };
39011     TraversingState.prototype._getAlpha = function () {
39012         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
39013     };
39014     TraversingState.prototype._setCurrentCamera = function () {
39015         _super.prototype._setCurrentCamera.call(this);
39016         this._adjustCameras();
39017     };
39018     TraversingState.prototype._adjustCameras = function () {
39019         if (this._previousNode == null) {
39020             return;
39021         }
39022         var lookat = this._camera.lookat.clone().sub(this._camera.position);
39023         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
39024         if (this._currentNode.fullPano) {
39025             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
39026         }
39027     };
39028     TraversingState.prototype._resetTransition = function () {
39029         this._alpha = 0;
39030         this._baseAlpha = 0;
39031         this._motionless = this._motionlessTransition();
39032     };
39033     TraversingState.prototype._applyRotation = function (camera) {
39034         if (camera == null) {
39035             return;
39036         }
39037         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
39038         var qInverse = q.clone().inverse();
39039         var offset = new THREE.Vector3();
39040         offset.copy(camera.lookat).sub(camera.position);
39041         offset.applyQuaternion(q);
39042         var length = offset.length();
39043         var phi = Math.atan2(offset.y, offset.x);
39044         phi += this._rotationDelta.phi;
39045         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
39046         theta += this._rotationDelta.theta;
39047         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
39048         offset.x = Math.sin(theta) * Math.cos(phi);
39049         offset.y = Math.sin(theta) * Math.sin(phi);
39050         offset.z = Math.cos(theta);
39051         offset.applyQuaternion(qInverse);
39052         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
39053     };
39054     TraversingState.prototype._applyRotationBasic = function (basicRotation) {
39055         var currentNode = this._currentNode;
39056         var previousNode = this._previousNode != null ?
39057             this.previousNode :
39058             this.currentNode;
39059         var currentCamera = this._currentCamera;
39060         var previousCamera = this._previousCamera;
39061         var currentTransform = this.currentTransform;
39062         var previousTransform = this.previousTransform != null ?
39063             this.previousTransform :
39064             this.currentTransform;
39065         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
39066         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
39067         var currentGPano = currentTransform.gpano;
39068         var previousGPano = previousTransform.gpano;
39069         if (currentNode.fullPano) {
39070             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
39071             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
39072         }
39073         else if (currentGPano != null &&
39074             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
39075             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
39076             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
39077         }
39078         else {
39079             currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
39080             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
39081         }
39082         if (previousNode.fullPano) {
39083             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
39084             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
39085         }
39086         else if (previousGPano != null &&
39087             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
39088             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
39089             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
39090         }
39091         else {
39092             previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
39093             previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
39094         }
39095         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
39096         currentCamera.lookat.fromArray(currentLookat);
39097         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
39098         previousCamera.lookat.fromArray(previousLookat);
39099     };
39100     TraversingState.prototype._updateZoom = function (animationSpeed) {
39101         var diff = this._desiredZoom - this._zoom;
39102         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
39103         if (diff === 0) {
39104             return;
39105         }
39106         else if (Math.abs(diff) < 2e-3) {
39107             this._zoom = this._desiredZoom;
39108             if (this._desiredLookat != null) {
39109                 this._desiredLookat = null;
39110             }
39111         }
39112         else {
39113             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
39114         }
39115     };
39116     TraversingState.prototype._updateLookat = function (animationSpeed) {
39117         if (this._desiredLookat === null) {
39118             return;
39119         }
39120         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
39121         if (Math.abs(diff) < 1e-6) {
39122             this._currentCamera.lookat.copy(this._desiredLookat);
39123             this._desiredLookat = null;
39124         }
39125         else {
39126             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
39127         }
39128     };
39129     TraversingState.prototype._updateRotation = function () {
39130         if (this._requestedRotationDelta != null) {
39131             var length_1 = this._rotationDelta.lengthSquared();
39132             var requestedLength = this._requestedRotationDelta.lengthSquared();
39133             if (requestedLength > length_1) {
39134                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
39135             }
39136             else {
39137                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
39138             }
39139             this._requestedRotationDelta = null;
39140             return;
39141         }
39142         if (this._rotationDelta.isZero) {
39143             return;
39144         }
39145         this._rotationDelta.multiply(this._rotationAcceleration);
39146         this._rotationDelta.threshold(this._rotationThreshold);
39147     };
39148     TraversingState.prototype._updateRotationBasic = function () {
39149         if (this._requestedBasicRotation != null) {
39150             var x = this._basicRotation[0];
39151             var y = this._basicRotation[1];
39152             var reqX = this._requestedBasicRotation[0];
39153             var reqY = this._requestedBasicRotation[1];
39154             if (Math.abs(reqX) > Math.abs(x)) {
39155                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
39156             }
39157             else {
39158                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
39159             }
39160             if (Math.abs(reqY) > Math.abs(y)) {
39161                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
39162             }
39163             else {
39164                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
39165             }
39166             this._requestedBasicRotation = null;
39167             return;
39168         }
39169         if (this._requestedBasicRotationUnbounded != null) {
39170             var reqX = this._requestedBasicRotationUnbounded[0];
39171             var reqY = this._requestedBasicRotationUnbounded[1];
39172             if (Math.abs(reqX) > 0) {
39173                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
39174             }
39175             if (Math.abs(reqY) > 0) {
39176                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
39177             }
39178             if (this._desiredLookat != null) {
39179                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
39180                 desiredBasicLookat[0] += reqX;
39181                 desiredBasicLookat[1] += reqY;
39182                 this._desiredLookat = new THREE.Vector3()
39183                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
39184             }
39185             this._requestedBasicRotationUnbounded = null;
39186         }
39187         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
39188             return;
39189         }
39190         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
39191         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
39192         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
39193             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
39194             this._basicRotation = [0, 0];
39195         }
39196     };
39197     TraversingState.prototype._clearRotation = function () {
39198         if (this._currentNode.fullPano) {
39199             return;
39200         }
39201         if (this._requestedRotationDelta != null) {
39202             this._requestedRotationDelta = null;
39203         }
39204         if (!this._rotationDelta.isZero) {
39205             this._rotationDelta.reset();
39206         }
39207         if (this._requestedBasicRotation != null) {
39208             this._requestedBasicRotation = null;
39209         }
39210         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
39211             this._basicRotation = [0, 0];
39212         }
39213     };
39214     TraversingState.prototype._setDesiredCenter = function () {
39215         if (this._desiredCenter == null) {
39216             return;
39217         }
39218         var lookatDirection = new THREE.Vector3()
39219             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
39220             .sub(this._currentCamera.position);
39221         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
39222         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
39223         this._desiredCenter = null;
39224     };
39225     TraversingState.prototype._setDesiredZoom = function () {
39226         this._desiredZoom =
39227             this._currentNode.fullPano || this._previousNode == null ?
39228                 this._zoom : 0;
39229     };
39230     return TraversingState;
39231 }(State_1.StateBase));
39232 exports.TraversingState = TraversingState;
39233
39234 },{"../../State":237,"@mapbox/unitbezier":2,"three":180}],354:[function(require,module,exports){
39235 "use strict";
39236 var __extends = (this && this.__extends) || (function () {
39237     var extendStatics = Object.setPrototypeOf ||
39238         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
39239         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
39240     return function (d, b) {
39241         extendStatics(d, b);
39242         function __() { this.constructor = d; }
39243         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
39244     };
39245 })();
39246 Object.defineProperty(exports, "__esModule", { value: true });
39247 var State_1 = require("../../State");
39248 var WaitingState = (function (_super) {
39249     __extends(WaitingState, _super);
39250     function WaitingState(state) {
39251         var _this = _super.call(this, state) || this;
39252         _this._zoom = 0;
39253         _this._adjustCameras();
39254         _this._motionless = _this._motionlessTransition();
39255         return _this;
39256     }
39257     WaitingState.prototype.traverse = function () {
39258         return new State_1.TraversingState(this);
39259     };
39260     WaitingState.prototype.wait = function () {
39261         throw new Error("Not implemented");
39262     };
39263     WaitingState.prototype.prepend = function (nodes) {
39264         _super.prototype.prepend.call(this, nodes);
39265         this._motionless = this._motionlessTransition();
39266     };
39267     WaitingState.prototype.set = function (nodes) {
39268         _super.prototype.set.call(this, nodes);
39269         this._motionless = this._motionlessTransition();
39270     };
39271     WaitingState.prototype.rotate = function (delta) { return; };
39272     WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
39273     WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
39274     WaitingState.prototype.rotateBasicWithoutInertia = function (basicRotation) { return; };
39275     WaitingState.prototype.rotateToBasic = function (basic) { return; };
39276     WaitingState.prototype.zoomIn = function (delta, reference) { return; };
39277     WaitingState.prototype.move = function (delta) {
39278         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
39279     };
39280     WaitingState.prototype.moveTo = function (position) {
39281         this._alpha = Math.max(0, Math.min(1, position));
39282     };
39283     WaitingState.prototype.update = function (fps) {
39284         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
39285     };
39286     WaitingState.prototype.setCenter = function (center) { return; };
39287     WaitingState.prototype.setZoom = function (zoom) { return; };
39288     WaitingState.prototype._getAlpha = function () {
39289         return this._motionless ? Math.round(this._alpha) : this._alpha;
39290     };
39291     WaitingState.prototype._setCurrentCamera = function () {
39292         _super.prototype._setCurrentCamera.call(this);
39293         this._adjustCameras();
39294     };
39295     WaitingState.prototype._adjustCameras = function () {
39296         if (this._previousNode == null) {
39297             return;
39298         }
39299         if (this._currentNode.fullPano) {
39300             var lookat = this._camera.lookat.clone().sub(this._camera.position);
39301             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
39302         }
39303         if (this._previousNode.fullPano) {
39304             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
39305             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
39306         }
39307     };
39308     return WaitingState;
39309 }(State_1.StateBase));
39310 exports.WaitingState = WaitingState;
39311
39312 },{"../../State":237}],355:[function(require,module,exports){
39313 "use strict";
39314 Object.defineProperty(exports, "__esModule", { value: true });
39315 var Observable_1 = require("rxjs/Observable");
39316 /**
39317  * @class ImageTileLoader
39318  *
39319  * @classdesc Represents a loader of image tiles.
39320  */
39321 var ImageTileLoader = (function () {
39322     /**
39323      * Create a new node image tile loader instance.
39324      *
39325      * @param {string} scheme - The URI scheme.
39326      * @param {string} host - The URI host.
39327      * @param {string} [origin] - The origin query param.
39328      */
39329     function ImageTileLoader(scheme, host, origin) {
39330         this._scheme = scheme;
39331         this._host = host;
39332         this._origin = origin != null ? "?origin=" + origin : "";
39333     }
39334     /**
39335      * Retrieve an image tile.
39336      *
39337      * @description Retrieve an image tile by specifying the area
39338      * as well as the scaled size.
39339      *
39340      * @param {string} identifier - The identifier of the image.
39341      * @param {number} x - The top left x pixel coordinate for the tile
39342      * in the original image.
39343      * @param {number} y - The top left y pixel coordinate for the tile
39344      * in the original image.
39345      * @param {number} w - The pixel width of the tile in the original image.
39346      * @param {number} h - The pixel height of the tile in the original image.
39347      * @param {number} scaledW - The scaled width of the returned tile.
39348      * @param {number} scaledH - The scaled height of the returned tile.
39349      */
39350     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
39351         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
39352         var url = this._scheme +
39353             "://" +
39354             this._host +
39355             characteristics +
39356             this._origin;
39357         var xmlHTTP = null;
39358         return [Observable_1.Observable.create(function (subscriber) {
39359                 xmlHTTP = new XMLHttpRequest();
39360                 xmlHTTP.open("GET", url, true);
39361                 xmlHTTP.responseType = "arraybuffer";
39362                 xmlHTTP.timeout = 15000;
39363                 xmlHTTP.onload = function (event) {
39364                     if (xmlHTTP.status !== 200) {
39365                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
39366                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
39367                         return;
39368                     }
39369                     var image = new Image();
39370                     image.crossOrigin = "Anonymous";
39371                     image.onload = function (e) {
39372                         subscriber.next(image);
39373                         subscriber.complete();
39374                     };
39375                     image.onerror = function (error) {
39376                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
39377                     };
39378                     var blob = new Blob([xmlHTTP.response]);
39379                     image.src = window.URL.createObjectURL(blob);
39380                 };
39381                 xmlHTTP.onerror = function (error) {
39382                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
39383                 };
39384                 xmlHTTP.ontimeout = function (error) {
39385                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
39386                 };
39387                 xmlHTTP.onabort = function (event) {
39388                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
39389                 };
39390                 xmlHTTP.send(null);
39391             }),
39392             function () {
39393                 if (xmlHTTP != null) {
39394                     xmlHTTP.abort();
39395                 }
39396             },
39397         ];
39398     };
39399     return ImageTileLoader;
39400 }());
39401 exports.ImageTileLoader = ImageTileLoader;
39402 exports.default = ImageTileLoader;
39403
39404 },{"rxjs/Observable":29}],356:[function(require,module,exports){
39405 "use strict";
39406 Object.defineProperty(exports, "__esModule", { value: true });
39407 /**
39408  * @class ImageTileStore
39409  *
39410  * @classdesc Represents a store for image tiles.
39411  */
39412 var ImageTileStore = (function () {
39413     /**
39414      * Create a new node image tile store instance.
39415      */
39416     function ImageTileStore() {
39417         this._images = {};
39418     }
39419     /**
39420      * Add an image tile to the store.
39421      *
39422      * @param {HTMLImageElement} image - The image tile.
39423      * @param {string} key - The identifier for the tile.
39424      * @param {number} level - The level of the tile.
39425      */
39426     ImageTileStore.prototype.addImage = function (image, key, level) {
39427         if (!(level in this._images)) {
39428             this._images[level] = {};
39429         }
39430         this._images[level][key] = image;
39431     };
39432     /**
39433      * Dispose the store.
39434      *
39435      * @description Disposes all cached assets.
39436      */
39437     ImageTileStore.prototype.dispose = function () {
39438         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
39439             var level = _a[_i];
39440             var levelImages = this._images[level];
39441             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
39442                 var key = _c[_b];
39443                 window.URL.revokeObjectURL(levelImages[key].src);
39444                 delete levelImages[key];
39445             }
39446             delete this._images[level];
39447         }
39448     };
39449     /**
39450      * Get an image tile from the store.
39451      *
39452      * @param {string} key - The identifier for the tile.
39453      * @param {number} level - The level of the tile.
39454      */
39455     ImageTileStore.prototype.getImage = function (key, level) {
39456         return this._images[level][key];
39457     };
39458     /**
39459      * Check if an image tile exist in the store.
39460      *
39461      * @param {string} key - The identifier for the tile.
39462      * @param {number} level - The level of the tile.
39463      */
39464     ImageTileStore.prototype.hasImage = function (key, level) {
39465         return level in this._images && key in this._images[level];
39466     };
39467     return ImageTileStore;
39468 }());
39469 exports.ImageTileStore = ImageTileStore;
39470 exports.default = ImageTileStore;
39471
39472 },{}],357:[function(require,module,exports){
39473 "use strict";
39474 /// <reference path="../../typings/index.d.ts" />
39475 Object.defineProperty(exports, "__esModule", { value: true });
39476 var Geo_1 = require("../Geo");
39477 /**
39478  * @class RegionOfInterestCalculator
39479  *
39480  * @classdesc Represents a calculator for regions of interest.
39481  */
39482 var RegionOfInterestCalculator = (function () {
39483     function RegionOfInterestCalculator() {
39484         this._viewportCoords = new Geo_1.ViewportCoords();
39485     }
39486     /**
39487      * Compute a region of interest based on the current render camera
39488      * and the viewport size.
39489      *
39490      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
39491      * @param {ISize} size - Viewport size in pixels.
39492      * @param {Transform} transform - Transform used for projections.
39493      *
39494      * @returns {IRegionOfInterest} A region of interest.
39495      */
39496     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
39497         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
39498         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
39499         this._clipBoundingBox(bbox);
39500         var viewportPixelWidth = 2 / size.width;
39501         var viewportPixelHeight = 2 / size.height;
39502         var centralViewportPixel = [
39503             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
39504             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
39505             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
39506             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
39507         ];
39508         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
39509         return {
39510             bbox: bbox,
39511             pixelHeight: cpbox.maxY - cpbox.minY,
39512             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
39513         };
39514     };
39515     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
39516         var points = [];
39517         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
39518         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
39519         for (var side = 0; side < 4; ++side) {
39520             var o = os[side];
39521             var d = ds[side];
39522             for (var i = 0; i < pointsPerSide; ++i) {
39523                 points.push([o[0] + d[0] * i / pointsPerSide,
39524                     o[1] + d[1] * i / pointsPerSide]);
39525             }
39526         }
39527         return points;
39528     };
39529     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
39530         var _this = this;
39531         var basicPoints = viewportPoints
39532             .map(function (point) {
39533             return _this._viewportCoords
39534                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
39535         });
39536         if (transform.gpano != null) {
39537             return this._boundingBoxPano(basicPoints);
39538         }
39539         else {
39540             return this._boundingBox(basicPoints);
39541         }
39542     };
39543     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
39544         var bbox = {
39545             maxX: Number.NEGATIVE_INFINITY,
39546             maxY: Number.NEGATIVE_INFINITY,
39547             minX: Number.POSITIVE_INFINITY,
39548             minY: Number.POSITIVE_INFINITY,
39549         };
39550         for (var i = 0; i < points.length; ++i) {
39551             bbox.minX = Math.min(bbox.minX, points[i][0]);
39552             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
39553             bbox.minY = Math.min(bbox.minY, points[i][1]);
39554             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
39555         }
39556         return bbox;
39557     };
39558     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
39559         var _this = this;
39560         var xs = [];
39561         var ys = [];
39562         for (var i = 0; i < points.length; ++i) {
39563             xs.push(points[i][0]);
39564             ys.push(points[i][1]);
39565         }
39566         xs.sort(function (a, b) { return _this._sign(a - b); });
39567         ys.sort(function (a, b) { return _this._sign(a - b); });
39568         var intervalX = this._intervalPano(xs);
39569         return {
39570             maxX: intervalX[1],
39571             maxY: ys[ys.length - 1],
39572             minX: intervalX[0],
39573             minY: ys[0],
39574         };
39575     };
39576     /**
39577      * Find the max interval between consecutive numbers.
39578      * Assumes numbers are between 0 and 1, sorted and that
39579      * x is equivalent to x + 1.
39580      */
39581     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
39582         var maxdx = 0;
39583         var maxi = -1;
39584         for (var i = 0; i < xs.length - 1; ++i) {
39585             var dx = xs[i + 1] - xs[i];
39586             if (dx > maxdx) {
39587                 maxdx = dx;
39588                 maxi = i;
39589             }
39590         }
39591         var loopdx = xs[0] + 1 - xs[xs.length - 1];
39592         if (loopdx > maxdx) {
39593             return [xs[0], xs[xs.length - 1]];
39594         }
39595         else {
39596             return [xs[maxi + 1], xs[maxi]];
39597         }
39598     };
39599     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
39600         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
39601         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
39602         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
39603         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
39604     };
39605     RegionOfInterestCalculator.prototype._sign = function (n) {
39606         return n > 0 ? 1 : n < 0 ? -1 : 0;
39607     };
39608     return RegionOfInterestCalculator;
39609 }());
39610 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
39611 exports.default = RegionOfInterestCalculator;
39612
39613 },{"../Geo":233}],358:[function(require,module,exports){
39614 "use strict";
39615 /// <reference path="../../typings/index.d.ts" />
39616 Object.defineProperty(exports, "__esModule", { value: true });
39617 var THREE = require("three");
39618 var Subject_1 = require("rxjs/Subject");
39619 /**
39620  * @class TextureProvider
39621  *
39622  * @classdesc Represents a provider of textures.
39623  */
39624 var TextureProvider = (function () {
39625     /**
39626      * Create a new node texture provider instance.
39627      *
39628      * @param {string} key - The identifier of the image for which to request tiles.
39629      * @param {number} width - The full width of the original image.
39630      * @param {number} height - The full height of the original image.
39631      * @param {number} tileSize - The size used when requesting tiles.
39632      * @param {HTMLImageElement} background - Image to use as background.
39633      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
39634      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
39635      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
39636      */
39637     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
39638         this._disposed = false;
39639         this._key = key;
39640         if (width <= 0 || height <= 0) {
39641             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
39642         }
39643         this._width = width;
39644         this._height = height;
39645         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
39646         this._currentLevel = -1;
39647         this._tileSize = tileSize;
39648         this._updated$ = new Subject_1.Subject();
39649         this._createdSubject$ = new Subject_1.Subject();
39650         this._created$ = this._createdSubject$
39651             .publishReplay(1)
39652             .refCount();
39653         this._createdSubscription = this._created$.subscribe(function () { });
39654         this._hasSubject$ = new Subject_1.Subject();
39655         this._has$ = this._hasSubject$
39656             .startWith(false)
39657             .publishReplay(1)
39658             .refCount();
39659         this._hasSubscription = this._has$.subscribe(function () { });
39660         this._abortFunctions = [];
39661         this._tileSubscriptions = {};
39662         this._renderedCurrentLevelTiles = {};
39663         this._renderedTiles = {};
39664         this._background = background;
39665         this._camera = null;
39666         this._imageTileLoader = imageTileLoader;
39667         this._imageTileStore = imageTileStore;
39668         this._renderer = renderer;
39669         this._renderTarget = null;
39670         this._roi = null;
39671     }
39672     Object.defineProperty(TextureProvider.prototype, "disposed", {
39673         /**
39674          * Get disposed.
39675          *
39676          * @returns {boolean} Value indicating whether provider has
39677          * been disposed.
39678          */
39679         get: function () {
39680             return this._disposed;
39681         },
39682         enumerable: true,
39683         configurable: true
39684     });
39685     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
39686         /**
39687          * Get hasTexture$.
39688          *
39689          * @returns {Observable<boolean>} Observable emitting
39690          * values indicating when the existance of a texture
39691          * changes.
39692          */
39693         get: function () {
39694             return this._has$;
39695         },
39696         enumerable: true,
39697         configurable: true
39698     });
39699     Object.defineProperty(TextureProvider.prototype, "key", {
39700         /**
39701          * Get key.
39702          *
39703          * @returns {boolean} The identifier of the image for
39704          * which to render textures.
39705          */
39706         get: function () {
39707             return this._key;
39708         },
39709         enumerable: true,
39710         configurable: true
39711     });
39712     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
39713         /**
39714          * Get textureUpdated$.
39715          *
39716          * @returns {Observable<boolean>} Observable emitting
39717          * values when an existing texture has been updated.
39718          */
39719         get: function () {
39720             return this._updated$;
39721         },
39722         enumerable: true,
39723         configurable: true
39724     });
39725     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
39726         /**
39727          * Get textureCreated$.
39728          *
39729          * @returns {Observable<boolean>} Observable emitting
39730          * values when a new texture has been created.
39731          */
39732         get: function () {
39733             return this._created$;
39734         },
39735         enumerable: true,
39736         configurable: true
39737     });
39738     /**
39739      * Abort all outstanding image tile requests.
39740      */
39741     TextureProvider.prototype.abort = function () {
39742         for (var key in this._tileSubscriptions) {
39743             if (!this._tileSubscriptions.hasOwnProperty(key)) {
39744                 continue;
39745             }
39746             this._tileSubscriptions[key].unsubscribe();
39747         }
39748         this._tileSubscriptions = {};
39749         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
39750             var abort = _a[_i];
39751             abort();
39752         }
39753         this._abortFunctions = [];
39754     };
39755     /**
39756      * Dispose the provider.
39757      *
39758      * @description Disposes all cached assets and
39759      * aborts all outstanding image tile requests.
39760      */
39761     TextureProvider.prototype.dispose = function () {
39762         if (this._disposed) {
39763             console.warn("Texture already disposed (" + this._key + ")");
39764             return;
39765         }
39766         this.abort();
39767         if (this._renderTarget != null) {
39768             this._renderTarget.dispose();
39769             this._renderTarget = null;
39770         }
39771         this._imageTileStore.dispose();
39772         this._imageTileStore = null;
39773         this._background = null;
39774         this._camera = null;
39775         this._imageTileLoader = null;
39776         this._renderer = null;
39777         this._roi = null;
39778         this._createdSubscription.unsubscribe();
39779         this._hasSubscription.unsubscribe();
39780         this._disposed = true;
39781     };
39782     /**
39783      * Set the region of interest.
39784      *
39785      * @description When the region of interest is set the
39786      * the tile level is determined and tiles for the region
39787      * are fetched from the store or the loader and renderedLevel
39788      * to the texture.
39789      *
39790      * @param {IRegionOfInterest} roi - Spatial edges to cache.
39791      */
39792     TextureProvider.prototype.setRegionOfInterest = function (roi) {
39793         if (this._width <= 0 || this._height <= 0) {
39794             return;
39795         }
39796         this._roi = roi;
39797         var width = 1 / this._roi.pixelWidth;
39798         var height = 1 / this._roi.pixelHeight;
39799         var size = Math.max(height, width);
39800         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
39801         if (currentLevel !== this._currentLevel) {
39802             this.abort();
39803             this._currentLevel = currentLevel;
39804             if (!(this._currentLevel in this._renderedTiles)) {
39805                 this._renderedTiles[this._currentLevel] = [];
39806             }
39807             this._renderedCurrentLevelTiles = {};
39808             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
39809                 var tile = _a[_i];
39810                 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
39811             }
39812         }
39813         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
39814         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
39815         var tiles = this._getTiles(topLeft, bottomRight);
39816         if (this._camera == null) {
39817             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
39818             this._camera.position.z = 1;
39819             var gl = this._renderer.getContext();
39820             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
39821             var backgroundSize = Math.max(this._width, this._height);
39822             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
39823             var targetWidth = Math.floor(scale * this._width);
39824             var targetHeight = Math.floor(scale * this._height);
39825             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
39826                 depthBuffer: false,
39827                 format: THREE.RGBFormat,
39828                 magFilter: THREE.LinearFilter,
39829                 minFilter: THREE.LinearFilter,
39830                 stencilBuffer: false,
39831             });
39832             this._renderToTarget(0, 0, this._width, this._height, this._background);
39833             this._createdSubject$.next(this._renderTarget.texture);
39834             this._hasSubject$.next(true);
39835         }
39836         this._fetchTiles(tiles);
39837     };
39838     TextureProvider.prototype.setTileSize = function (tileSize) {
39839         this._tileSize = tileSize;
39840     };
39841     /**
39842      * Update the image used as background for the texture.
39843      *
39844      * @param {HTMLImageElement} background - The background image.
39845      */
39846     TextureProvider.prototype.updateBackground = function (background) {
39847         this._background = background;
39848     };
39849     /**
39850      * Retrieve an image tile.
39851      *
39852      * @description Retrieve an image tile and render it to the
39853      * texture. Add the tile to the store and emit to the updated
39854      * observable.
39855      *
39856      * @param {Array<number>} tile - The tile coordinates.
39857      * @param {number} level - The tile level.
39858      * @param {number} x - The top left x pixel coordinate of the tile.
39859      * @param {number} y - The top left y pixel coordinate of the tile.
39860      * @param {number} w - The pixel width of the tile.
39861      * @param {number} h - The pixel height of the tile.
39862      * @param {number} scaledW - The scaled width of the returned tile.
39863      * @param {number} scaledH - The scaled height of the returned tile.
39864      */
39865     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
39866         var _this = this;
39867         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
39868         var tile$ = getTile[0];
39869         var abort = getTile[1];
39870         this._abortFunctions.push(abort);
39871         var tileKey = this._tileKey(this._tileSize, tile);
39872         var subscription = tile$
39873             .subscribe(function (image) {
39874             _this._renderToTarget(x, y, w, h, image);
39875             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
39876             _this._removeFromArray(abort, _this._abortFunctions);
39877             _this._setTileRendered(tile, _this._currentLevel);
39878             _this._imageTileStore.addImage(image, tileKey, level);
39879             _this._updated$.next(true);
39880         }, function (error) {
39881             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
39882             _this._removeFromArray(abort, _this._abortFunctions);
39883             console.error(error);
39884         });
39885         if (!subscription.closed) {
39886             this._tileSubscriptions[tileKey] = subscription;
39887         }
39888     };
39889     /**
39890      * Retrieve image tiles.
39891      *
39892      * @description Retrieve a image tiles and render them to the
39893      * texture. Retrieve from store if it exists, otherwise Retrieve
39894      * from loader.
39895      *
39896      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
39897      * retrieve.
39898      */
39899     TextureProvider.prototype._fetchTiles = function (tiles) {
39900         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
39901         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
39902             var tile = tiles_1[_i];
39903             var tileKey = this._tileKey(this._tileSize, tile);
39904             if (tileKey in this._renderedCurrentLevelTiles ||
39905                 tileKey in this._tileSubscriptions) {
39906                 continue;
39907             }
39908             var tileX = tileSize * tile[0];
39909             var tileY = tileSize * tile[1];
39910             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
39911             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
39912             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
39913                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
39914                 this._setTileRendered(tile, this._currentLevel);
39915                 this._updated$.next(true);
39916                 continue;
39917             }
39918             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
39919             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
39920             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
39921         }
39922     };
39923     /**
39924      * Get tile coordinates for a point using the current level.
39925      *
39926      * @param {Array<number>} point - Point in basic coordinates.
39927      *
39928      * @returns {Array<number>} x and y tile coodinates.
39929      */
39930     TextureProvider.prototype._getTileCoords = function (point) {
39931         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
39932         var maxX = Math.ceil(this._width / tileSize) - 1;
39933         var maxY = Math.ceil(this._height / tileSize) - 1;
39934         return [
39935             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
39936             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
39937         ];
39938     };
39939     /**
39940      * Get tile coordinates for all tiles contained in a bounding
39941      * box.
39942      *
39943      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
39944      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
39945      *
39946      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
39947      */
39948     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
39949         var xs = [];
39950         if (topLeft[0] > bottomRight[0]) {
39951             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
39952             var maxX = Math.ceil(this._width / tileSize) - 1;
39953             for (var x = topLeft[0]; x <= maxX; x++) {
39954                 xs.push(x);
39955             }
39956             for (var x = 0; x <= bottomRight[0]; x++) {
39957                 xs.push(x);
39958             }
39959         }
39960         else {
39961             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
39962                 xs.push(x);
39963             }
39964         }
39965         var tiles = [];
39966         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
39967             var x = xs_1[_i];
39968             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
39969                 tiles.push([x, y]);
39970             }
39971         }
39972         return tiles;
39973     };
39974     /**
39975      * Remove an item from an array if it exists in array.
39976      *
39977      * @param {T} item - Item to remove.
39978      * @param {Array<T>} array - Array from which item should be removed.
39979      */
39980     TextureProvider.prototype._removeFromArray = function (item, array) {
39981         var index = array.indexOf(item);
39982         if (index !== -1) {
39983             array.splice(index, 1);
39984         }
39985     };
39986     /**
39987      * Remove an item from a dictionary.
39988      *
39989      * @param {string} key - Key of the item to remove.
39990      * @param {Object} dict - Dictionary from which item should be removed.
39991      */
39992     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
39993         if (key in dict) {
39994             delete dict[key];
39995         }
39996     };
39997     /**
39998      * Render an image tile to the target texture.
39999      *
40000      * @param {number} x - The top left x pixel coordinate of the tile.
40001      * @param {number} y - The top left y pixel coordinate of the tile.
40002      * @param {number} w - The pixel width of the tile.
40003      * @param {number} h - The pixel height of the tile.
40004      * @param {HTMLImageElement} background - The image tile to render.
40005      */
40006     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
40007         var texture = new THREE.Texture(image);
40008         texture.minFilter = THREE.LinearFilter;
40009         texture.needsUpdate = true;
40010         var geometry = new THREE.PlaneGeometry(w, h);
40011         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
40012         var mesh = new THREE.Mesh(geometry, material);
40013         mesh.position.x = -this._width / 2 + x + w / 2;
40014         mesh.position.y = this._height / 2 - y - h / 2;
40015         var scene = new THREE.Scene();
40016         scene.add(mesh);
40017         this._renderer.render(scene, this._camera, this._renderTarget);
40018         this._renderer.setRenderTarget(undefined);
40019         scene.remove(mesh);
40020         geometry.dispose();
40021         material.dispose();
40022         texture.dispose();
40023     };
40024     /**
40025      * Mark a tile as rendered.
40026      *
40027      * @description Clears tiles marked as rendered in other
40028      * levels of the tile pyramid  if they were rendered on
40029      * top of or below the tile.
40030      *
40031      * @param {Arrary<number>} tile - The tile coordinates.
40032      * @param {number} level - Tile level of the tile coordinates.
40033      */
40034     TextureProvider.prototype._setTileRendered = function (tile, level) {
40035         var otherLevels = Object.keys(this._renderedTiles)
40036             .map(function (key) {
40037             return parseInt(key, 10);
40038         })
40039             .filter(function (renderedLevel) {
40040             return renderedLevel !== level;
40041         });
40042         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
40043             var otherLevel = otherLevels_1[_i];
40044             var scale = Math.pow(2, otherLevel - level);
40045             if (otherLevel < level) {
40046                 var x = Math.floor(scale * tile[0]);
40047                 var y = Math.floor(scale * tile[1]);
40048                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
40049                     var otherTile = _b[_a];
40050                     if (otherTile[0] === x && otherTile[1] === y) {
40051                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
40052                         this._renderedTiles[otherLevel].splice(index, 1);
40053                     }
40054                 }
40055             }
40056             else {
40057                 var startX = scale * tile[0];
40058                 var endX = startX + scale - 1;
40059                 var startY = scale * tile[1];
40060                 var endY = startY + scale - 1;
40061                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
40062                     var otherTile = _d[_c];
40063                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
40064                         otherTile[1] >= startY && otherTile[1] <= endY) {
40065                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
40066                         this._renderedTiles[otherLevel].splice(index, 1);
40067                     }
40068                 }
40069             }
40070             if (this._renderedTiles[otherLevel].length === 0) {
40071                 delete this._renderedTiles[otherLevel];
40072             }
40073         }
40074         this._renderedTiles[level].push(tile);
40075         this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
40076     };
40077     /**
40078      * Create a tile key from a tile coordinates.
40079      *
40080      * @description Tile keys are used as a hash for
40081      * storing the tile in a dictionary.
40082      *
40083      * @param {number} tileSize - The tile size.
40084      * @param {Arrary<number>} tile - The tile coordinates.
40085      */
40086     TextureProvider.prototype._tileKey = function (tileSize, tile) {
40087         return tileSize + "-" + tile[0] + "-" + tile[1];
40088     };
40089     return TextureProvider;
40090 }());
40091 exports.TextureProvider = TextureProvider;
40092 exports.default = TextureProvider;
40093
40094 },{"rxjs/Subject":34,"three":180}],359:[function(require,module,exports){
40095 "use strict";
40096 Object.defineProperty(exports, "__esModule", { value: true });
40097 var DOM = (function () {
40098     function DOM(doc) {
40099         this._document = !!doc ? doc : document;
40100     }
40101     Object.defineProperty(DOM.prototype, "document", {
40102         get: function () {
40103             return this._document;
40104         },
40105         enumerable: true,
40106         configurable: true
40107     });
40108     DOM.prototype.createElement = function (tagName, className, container) {
40109         var element = this._document.createElement(tagName);
40110         if (!!className) {
40111             element.className = className;
40112         }
40113         if (!!container) {
40114             container.appendChild(element);
40115         }
40116         return element;
40117     };
40118     return DOM;
40119 }());
40120 exports.DOM = DOM;
40121 exports.default = DOM;
40122
40123 },{}],360:[function(require,module,exports){
40124 "use strict";
40125 Object.defineProperty(exports, "__esModule", { value: true });
40126 var EventEmitter = (function () {
40127     function EventEmitter() {
40128         this._events = {};
40129     }
40130     /**
40131      * Subscribe to an event by its name.
40132      * @param {string }eventType - The name of the event to subscribe to.
40133      * @param {any} fn - The handler called when the event occurs.
40134      */
40135     EventEmitter.prototype.on = function (eventType, fn) {
40136         this._events[eventType] = this._events[eventType] || [];
40137         this._events[eventType].push(fn);
40138         return;
40139     };
40140     /**
40141      * Unsubscribe from an event by its name.
40142      * @param {string} eventType - The name of the event to subscribe to.
40143      * @param {any} fn - The handler to remove.
40144      */
40145     EventEmitter.prototype.off = function (eventType, fn) {
40146         if (!eventType) {
40147             this._events = {};
40148             return;
40149         }
40150         if (!this._listens(eventType)) {
40151             var idx = this._events[eventType].indexOf(fn);
40152             if (idx >= 0) {
40153                 this._events[eventType].splice(idx, 1);
40154             }
40155             if (this._events[eventType].length) {
40156                 delete this._events[eventType];
40157             }
40158         }
40159         else {
40160             delete this._events[eventType];
40161         }
40162         return;
40163     };
40164     EventEmitter.prototype.fire = function (eventType, data) {
40165         if (!this._listens(eventType)) {
40166             return;
40167         }
40168         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
40169             var fn = _a[_i];
40170             fn.call(this, data);
40171         }
40172         return;
40173     };
40174     EventEmitter.prototype._listens = function (eventType) {
40175         return !!(this._events && this._events[eventType]);
40176     };
40177     return EventEmitter;
40178 }());
40179 exports.EventEmitter = EventEmitter;
40180 exports.default = EventEmitter;
40181
40182 },{}],361:[function(require,module,exports){
40183 "use strict";
40184 Object.defineProperty(exports, "__esModule", { value: true });
40185 var Viewer_1 = require("../Viewer");
40186 var Settings = (function () {
40187     function Settings() {
40188     }
40189     Settings.setOptions = function (options) {
40190         Settings._baseImageSize = options.baseImageSize != null ?
40191             options.baseImageSize :
40192             Viewer_1.ImageSize.Size640;
40193         Settings._basePanoramaSize = options.basePanoramaSize != null ?
40194             options.basePanoramaSize :
40195             Viewer_1.ImageSize.Size2048;
40196         Settings._maxImageSize = options.maxImageSize != null ?
40197             options.maxImageSize :
40198             Viewer_1.ImageSize.Size2048;
40199     };
40200     Object.defineProperty(Settings, "baseImageSize", {
40201         get: function () {
40202             return Settings._baseImageSize;
40203         },
40204         enumerable: true,
40205         configurable: true
40206     });
40207     Object.defineProperty(Settings, "basePanoramaSize", {
40208         get: function () {
40209             return Settings._basePanoramaSize;
40210         },
40211         enumerable: true,
40212         configurable: true
40213     });
40214     Object.defineProperty(Settings, "maxImageSize", {
40215         get: function () {
40216             return Settings._maxImageSize;
40217         },
40218         enumerable: true,
40219         configurable: true
40220     });
40221     return Settings;
40222 }());
40223 exports.Settings = Settings;
40224 exports.default = Settings;
40225
40226 },{"../Viewer":241}],362:[function(require,module,exports){
40227 "use strict";
40228 Object.defineProperty(exports, "__esModule", { value: true });
40229 function isBrowser() {
40230     return typeof window !== "undefined" && typeof document !== "undefined";
40231 }
40232 exports.isBrowser = isBrowser;
40233 function isArraySupported() {
40234     return !!(Array.prototype &&
40235         Array.prototype.filter &&
40236         Array.prototype.indexOf &&
40237         Array.prototype.map);
40238 }
40239 exports.isArraySupported = isArraySupported;
40240 function isFunctionSupported() {
40241     return !!(Function.prototype && Function.prototype.bind);
40242 }
40243 exports.isFunctionSupported = isFunctionSupported;
40244 function isJSONSupported() {
40245     return "JSON" in window && "parse" in JSON && "stringify" in JSON;
40246 }
40247 exports.isJSONSupported = isJSONSupported;
40248 function isObjectSupported() {
40249     return !!(Object.keys &&
40250         Object.assign);
40251 }
40252 exports.isObjectSupported = isObjectSupported;
40253 var isWebGLSupportedCache = undefined;
40254 function isWebGLSupportedCached() {
40255     if (isWebGLSupportedCache === undefined) {
40256         isWebGLSupportedCache = isWebGLSupported();
40257     }
40258     return isWebGLSupportedCache;
40259 }
40260 exports.isWebGLSupportedCached = isWebGLSupportedCached;
40261 function isWebGLSupported() {
40262     var webGLContextAttributes = {
40263         alpha: false,
40264         antialias: false,
40265         depth: true,
40266         failIfMajorPerformanceCaveat: false,
40267         premultipliedAlpha: true,
40268         preserveDrawingBuffer: false,
40269         stencil: true,
40270     };
40271     var canvas = document.createElement("canvas");
40272     var context = canvas.getContext("webgl", webGLContextAttributes) ||
40273         canvas.getContext("experimental-webgl", webGLContextAttributes);
40274     if (!context) {
40275         return false;
40276     }
40277     var requiredExtensions = [
40278         "OES_standard_derivatives",
40279     ];
40280     var supportedExtensions = context.getSupportedExtensions();
40281     for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
40282         var requiredExtension = requiredExtensions_1[_i];
40283         if (supportedExtensions.indexOf(requiredExtension) === -1) {
40284             return false;
40285         }
40286     }
40287     return true;
40288 }
40289 exports.isWebGLSupported = isWebGLSupported;
40290
40291 },{}],363:[function(require,module,exports){
40292 "use strict";
40293 Object.defineProperty(exports, "__esModule", { value: true });
40294 var Urls = (function () {
40295     function Urls() {
40296     }
40297     Object.defineProperty(Urls, "tileScheme", {
40298         get: function () {
40299             return "https";
40300         },
40301         enumerable: true,
40302         configurable: true
40303     });
40304     Object.defineProperty(Urls, "tileDomain", {
40305         get: function () {
40306             return "d2qb1440i7l50o.cloudfront.net";
40307         },
40308         enumerable: true,
40309         configurable: true
40310     });
40311     Object.defineProperty(Urls, "origin", {
40312         get: function () {
40313             return "mapillary.webgl";
40314         },
40315         enumerable: true,
40316         configurable: true
40317     });
40318     Urls.thumbnail = function (key, size) {
40319         return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
40320     };
40321     Urls.falcorModel = function (clientId) {
40322         return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
40323     };
40324     Urls.protoMesh = function (key) {
40325         return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
40326     };
40327     return Urls;
40328 }());
40329 exports.Urls = Urls;
40330 exports.default = Urls;
40331
40332 },{}],364:[function(require,module,exports){
40333 "use strict";
40334 Object.defineProperty(exports, "__esModule", { value: true });
40335 /**
40336  * Enumeration for alignments
40337  * @enum {number}
40338  * @readonly
40339  */
40340 var Alignment;
40341 (function (Alignment) {
40342     /**
40343      * Align to bottom
40344      */
40345     Alignment[Alignment["Bottom"] = 0] = "Bottom";
40346     /**
40347      * Align to bottom left
40348      */
40349     Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
40350     /**
40351      * Align to bottom right
40352      */
40353     Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
40354     /**
40355      * Align to center
40356      */
40357     Alignment[Alignment["Center"] = 3] = "Center";
40358     /**
40359      * Align to left
40360      */
40361     Alignment[Alignment["Left"] = 4] = "Left";
40362     /**
40363      * Align to right
40364      */
40365     Alignment[Alignment["Right"] = 5] = "Right";
40366     /**
40367      * Align to top
40368      */
40369     Alignment[Alignment["Top"] = 6] = "Top";
40370     /**
40371      * Align to top left
40372      */
40373     Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
40374     /**
40375      * Align to top right
40376      */
40377     Alignment[Alignment["TopRight"] = 8] = "TopRight";
40378 })(Alignment = exports.Alignment || (exports.Alignment = {}));
40379 exports.default = Alignment;
40380
40381 },{}],365:[function(require,module,exports){
40382 "use strict";
40383 Object.defineProperty(exports, "__esModule", { value: true });
40384 require("rxjs/add/operator/bufferCount");
40385 require("rxjs/add/operator/delay");
40386 require("rxjs/add/operator/distinctUntilChanged");
40387 require("rxjs/add/operator/map");
40388 require("rxjs/add/operator/switchMap");
40389 var CacheService = (function () {
40390     function CacheService(graphService, stateService) {
40391         this._graphService = graphService;
40392         this._stateService = stateService;
40393         this._started = false;
40394     }
40395     Object.defineProperty(CacheService.prototype, "started", {
40396         get: function () {
40397             return this._started;
40398         },
40399         enumerable: true,
40400         configurable: true
40401     });
40402     CacheService.prototype.start = function () {
40403         var _this = this;
40404         if (this._started) {
40405             return;
40406         }
40407         this._uncacheSubscription = this._stateService.currentState$
40408             .distinctUntilChanged(undefined, function (frame) {
40409             return frame.state.currentNode.key;
40410         })
40411             .map(function (frame) {
40412             return frame.state.trajectory
40413                 .map(function (n) {
40414                 return n.key;
40415             });
40416         })
40417             .bufferCount(1, 5)
40418             .switchMap(function (keepKeysBuffer) {
40419             var keepKeys = keepKeysBuffer[0];
40420             return _this._graphService.uncache$(keepKeys);
40421         })
40422             .subscribe(function () { });
40423         this._started = true;
40424     };
40425     CacheService.prototype.stop = function () {
40426         if (!this._started) {
40427             return;
40428         }
40429         this._uncacheSubscription.unsubscribe();
40430         this._uncacheSubscription = null;
40431         this._started = false;
40432     };
40433     return CacheService;
40434 }());
40435 exports.CacheService = CacheService;
40436 exports.default = CacheService;
40437
40438 },{"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/delay":56,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/switchMap":80}],366:[function(require,module,exports){
40439 "use strict";
40440 Object.defineProperty(exports, "__esModule", { value: true });
40441 var Component_1 = require("../Component");
40442 var ComponentController = (function () {
40443     function ComponentController(container, navigator, observer, key, options, componentService) {
40444         var _this = this;
40445         this._container = container;
40446         this._observer = observer;
40447         this._navigator = navigator;
40448         this._options = options != null ? options : {};
40449         this._key = key;
40450         this._navigable = key == null;
40451         this._componentService = !!componentService ?
40452             componentService :
40453             new Component_1.ComponentService(this._container, this._navigator);
40454         this._coverComponent = this._componentService.getCover();
40455         this._initializeComponents();
40456         if (key) {
40457             this._initilizeCoverComponent();
40458             this._subscribeCoverComponent();
40459         }
40460         else {
40461             this._navigator.movedToKey$
40462                 .first(function (k) {
40463                 return k != null;
40464             })
40465                 .subscribe(function (k) {
40466                 _this._key = k;
40467                 _this._componentService.deactivateCover();
40468                 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
40469                 _this._subscribeCoverComponent();
40470                 _this._navigator.stateService.start();
40471                 _this._observer.startEmit();
40472             });
40473         }
40474     }
40475     Object.defineProperty(ComponentController.prototype, "navigable", {
40476         get: function () {
40477             return this._navigable;
40478         },
40479         enumerable: true,
40480         configurable: true
40481     });
40482     ComponentController.prototype.get = function (name) {
40483         return this._componentService.get(name);
40484     };
40485     ComponentController.prototype.activate = function (name) {
40486         this._componentService.activate(name);
40487     };
40488     ComponentController.prototype.activateCover = function () {
40489         this._coverComponent.configure({ state: Component_1.CoverState.Visible });
40490     };
40491     ComponentController.prototype.deactivate = function (name) {
40492         this._componentService.deactivate(name);
40493     };
40494     ComponentController.prototype.deactivateCover = function () {
40495         this._coverComponent.configure({ state: Component_1.CoverState.Loading });
40496     };
40497     ComponentController.prototype.resize = function () {
40498         this._componentService.resize();
40499     };
40500     ComponentController.prototype._initializeComponents = function () {
40501         var options = this._options;
40502         this._uFalse(options.background, "background");
40503         this._uFalse(options.debug, "debug");
40504         this._uFalse(options.image, "image");
40505         this._uFalse(options.marker, "marker");
40506         this._uFalse(options.navigation, "navigation");
40507         this._uFalse(options.popup, "popup");
40508         this._uFalse(options.route, "route");
40509         this._uFalse(options.slider, "slider");
40510         this._uFalse(options.tag, "tag");
40511         this._uTrue(options.attribution, "attribution");
40512         this._uTrue(options.bearing, "bearing");
40513         this._uTrue(options.cache, "cache");
40514         this._uTrue(options.direction, "direction");
40515         this._uTrue(options.imagePlane, "imagePlane");
40516         this._uTrue(options.keyboard, "keyboard");
40517         this._uTrue(options.loading, "loading");
40518         this._uTrue(options.mouse, "mouse");
40519         this._uTrue(options.sequence, "sequence");
40520         this._uTrue(options.stats, "stats");
40521     };
40522     ComponentController.prototype._initilizeCoverComponent = function () {
40523         var options = this._options;
40524         this._coverComponent.configure({ key: this._key });
40525         if (options.cover === undefined || options.cover) {
40526             this.activateCover();
40527         }
40528         else {
40529             this.deactivateCover();
40530         }
40531     };
40532     ComponentController.prototype._setNavigable = function (navigable) {
40533         if (this._navigable === navigable) {
40534             return;
40535         }
40536         this._navigable = navigable;
40537         this._observer.navigable$.next(navigable);
40538     };
40539     ComponentController.prototype._subscribeCoverComponent = function () {
40540         var _this = this;
40541         this._coverComponent.configuration$.subscribe(function (conf) {
40542             if (conf.state === Component_1.CoverState.Loading) {
40543                 _this._navigator.stateService.currentKey$
40544                     .first()
40545                     .switchMap(function (key) {
40546                     var keyChanged = key == null || key !== conf.key;
40547                     if (keyChanged) {
40548                         _this._setNavigable(false);
40549                     }
40550                     return keyChanged ?
40551                         _this._navigator.moveToKey$(conf.key) :
40552                         _this._navigator.stateService.currentNode$
40553                             .first();
40554                 })
40555                     .subscribe(function (node) {
40556                     _this._navigator.stateService.start();
40557                     _this._observer.startEmit();
40558                     _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
40559                     _this._componentService.deactivateCover();
40560                     _this._setNavigable(true);
40561                 }, function (error) {
40562                     console.error("Failed to deactivate cover.", error);
40563                     _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
40564                 });
40565             }
40566             else if (conf.state === Component_1.CoverState.Visible) {
40567                 _this._observer.stopEmit();
40568                 _this._navigator.stateService.stop();
40569                 _this._componentService.activateCover();
40570                 _this._setNavigable(conf.key == null);
40571             }
40572         });
40573     };
40574     ComponentController.prototype._uFalse = function (option, name) {
40575         if (option === undefined) {
40576             this._componentService.deactivate(name);
40577             return;
40578         }
40579         if (typeof option === "boolean") {
40580             if (option) {
40581                 this._componentService.activate(name);
40582             }
40583             else {
40584                 this._componentService.deactivate(name);
40585             }
40586             return;
40587         }
40588         this._componentService.configure(name, option);
40589         this._componentService.activate(name);
40590     };
40591     ComponentController.prototype._uTrue = function (option, name) {
40592         if (option === undefined) {
40593             this._componentService.activate(name);
40594             return;
40595         }
40596         if (typeof option === "boolean") {
40597             if (option) {
40598                 this._componentService.activate(name);
40599             }
40600             else {
40601                 this._componentService.deactivate(name);
40602             }
40603             return;
40604         }
40605         this._componentService.configure(name, option);
40606         this._componentService.activate(name);
40607     };
40608     return ComponentController;
40609 }());
40610 exports.ComponentController = ComponentController;
40611
40612 },{"../Component":230}],367:[function(require,module,exports){
40613 "use strict";
40614 Object.defineProperty(exports, "__esModule", { value: true });
40615 var Render_1 = require("../Render");
40616 var Utils_1 = require("../Utils");
40617 var Viewer_1 = require("../Viewer");
40618 var Container = (function () {
40619     function Container(id, stateService, options, dom) {
40620         this.id = id;
40621         this._dom = !!dom ? dom : new Utils_1.DOM();
40622         this._container = this._dom.document.getElementById(id);
40623         if (!this._container) {
40624             throw new Error("Container '" + id + "' not found.");
40625         }
40626         this._container.classList.add("mapillary-js");
40627         this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
40628         this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
40629         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
40630         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
40631         this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
40632         this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
40633         this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
40634         this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
40635         this.spriteService = new Viewer_1.SpriteService(options.sprite);
40636     }
40637     Object.defineProperty(Container.prototype, "element", {
40638         get: function () {
40639             return this._container;
40640         },
40641         enumerable: true,
40642         configurable: true
40643     });
40644     Object.defineProperty(Container.prototype, "canvasContainer", {
40645         get: function () {
40646             return this._canvasContainer;
40647         },
40648         enumerable: true,
40649         configurable: true
40650     });
40651     return Container;
40652 }());
40653 exports.Container = Container;
40654 exports.default = Container;
40655
40656 },{"../Render":236,"../Utils":240,"../Viewer":241}],368:[function(require,module,exports){
40657 "use strict";
40658 Object.defineProperty(exports, "__esModule", { value: true });
40659 /**
40660  * Enumeration for image sizes
40661  * @enum {number}
40662  * @readonly
40663  * @description Image sizes in pixels for the long side of the image.
40664  */
40665 var ImageSize;
40666 (function (ImageSize) {
40667     /**
40668      * 320 pixels image size
40669      */
40670     ImageSize[ImageSize["Size320"] = 320] = "Size320";
40671     /**
40672      * 640 pixels image size
40673      */
40674     ImageSize[ImageSize["Size640"] = 640] = "Size640";
40675     /**
40676      * 1024 pixels image size
40677      */
40678     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
40679     /**
40680      * 2048 pixels image size
40681      */
40682     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
40683 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
40684
40685 },{}],369:[function(require,module,exports){
40686 "use strict";
40687 Object.defineProperty(exports, "__esModule", { value: true });
40688 var Observable_1 = require("rxjs/Observable");
40689 var KeyboardService = (function () {
40690     function KeyboardService(canvasContainer) {
40691         this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown");
40692     }
40693     Object.defineProperty(KeyboardService.prototype, "keyDown$", {
40694         get: function () {
40695             return this._keyDown$;
40696         },
40697         enumerable: true,
40698         configurable: true
40699     });
40700     return KeyboardService;
40701 }());
40702 exports.KeyboardService = KeyboardService;
40703 exports.default = KeyboardService;
40704
40705 },{"rxjs/Observable":29}],370:[function(require,module,exports){
40706 "use strict";
40707 /// <reference path="../../typings/index.d.ts" />
40708 Object.defineProperty(exports, "__esModule", { value: true });
40709 var _ = require("underscore");
40710 var Subject_1 = require("rxjs/Subject");
40711 require("rxjs/add/operator/debounceTime");
40712 require("rxjs/add/operator/distinctUntilChanged");
40713 require("rxjs/add/operator/map");
40714 require("rxjs/add/operator/publishReplay");
40715 require("rxjs/add/operator/scan");
40716 require("rxjs/add/operator/startWith");
40717 var LoadingService = (function () {
40718     function LoadingService() {
40719         this._loadersSubject$ = new Subject_1.Subject();
40720         this._loaders$ = this._loadersSubject$
40721             .scan(function (loaders, loader) {
40722             if (loader.task !== undefined) {
40723                 loaders[loader.task] = loader.loading;
40724             }
40725             return loaders;
40726         }, {})
40727             .startWith({})
40728             .publishReplay(1)
40729             .refCount();
40730     }
40731     Object.defineProperty(LoadingService.prototype, "loading$", {
40732         get: function () {
40733             return this._loaders$
40734                 .map(function (loaders) {
40735                 return _.reduce(loaders, function (loader, acc) {
40736                     return (loader || acc);
40737                 }, false);
40738             })
40739                 .debounceTime(100)
40740                 .distinctUntilChanged();
40741         },
40742         enumerable: true,
40743         configurable: true
40744     });
40745     LoadingService.prototype.taskLoading$ = function (task) {
40746         return this._loaders$
40747             .map(function (loaders) {
40748             return !!loaders[task];
40749         })
40750             .debounceTime(100)
40751             .distinctUntilChanged();
40752     };
40753     LoadingService.prototype.startLoading = function (task) {
40754         this._loadersSubject$.next({ loading: true, task: task });
40755     };
40756     LoadingService.prototype.stopLoading = function (task) {
40757         this._loadersSubject$.next({ loading: false, task: task });
40758     };
40759     return LoadingService;
40760 }());
40761 exports.LoadingService = LoadingService;
40762 exports.default = LoadingService;
40763
40764 },{"rxjs/Subject":34,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/startWith":79,"underscore":182}],371:[function(require,module,exports){
40765 "use strict";
40766 Object.defineProperty(exports, "__esModule", { value: true });
40767 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40768 var Observable_1 = require("rxjs/Observable");
40769 var Subject_1 = require("rxjs/Subject");
40770 require("rxjs/add/observable/fromEvent");
40771 require("rxjs/add/operator/distinctUntilChanged");
40772 require("rxjs/add/operator/filter");
40773 require("rxjs/add/operator/map");
40774 require("rxjs/add/operator/merge");
40775 require("rxjs/add/operator/mergeMap");
40776 require("rxjs/add/operator/publishReplay");
40777 require("rxjs/add/operator/scan");
40778 require("rxjs/add/operator/switchMap");
40779 require("rxjs/add/operator/withLatestFrom");
40780 var Geo_1 = require("../Geo");
40781 var MouseService = (function () {
40782     function MouseService(container, canvasContainer, domContainer, doc, viewportCoords) {
40783         var _this = this;
40784         this._canvasContainer = canvasContainer;
40785         this._domContainer = domContainer;
40786         this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
40787         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
40788         this._active$ = this._activeSubject$
40789             .distinctUntilChanged()
40790             .publishReplay(1)
40791             .refCount();
40792         this._claimMouse$ = new Subject_1.Subject();
40793         this._claimWheel$ = new Subject_1.Subject();
40794         this._deferPixelClaims$ = new Subject_1.Subject();
40795         this._deferPixels$ = this._deferPixelClaims$
40796             .scan(function (claims, claim) {
40797             if (claim.deferPixels == null) {
40798                 delete claims[claim.name];
40799             }
40800             else {
40801                 claims[claim.name] = claim.deferPixels;
40802             }
40803             return claims;
40804         }, {})
40805             .map(function (claims) {
40806             var deferPixelMax = -1;
40807             for (var key in claims) {
40808                 if (!claims.hasOwnProperty(key)) {
40809                     continue;
40810                 }
40811                 var deferPixels = claims[key];
40812                 if (deferPixels > deferPixelMax) {
40813                     deferPixelMax = deferPixels;
40814                 }
40815             }
40816             return deferPixelMax;
40817         })
40818             .startWith(-1)
40819             .publishReplay(1)
40820             .refCount();
40821         this._deferPixels$.subscribe(function () { });
40822         this._documentMouseMove$ = Observable_1.Observable.fromEvent(doc, "mousemove");
40823         this._documentMouseUp$ = Observable_1.Observable.fromEvent(doc, "mouseup");
40824         this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
40825         this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
40826         this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
40827         this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
40828         this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
40829         this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
40830         this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
40831         this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
40832         this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
40833         this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
40834         this._dblClick$ = Observable_1.Observable
40835             .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
40836             .bufferCount(3, 1)
40837             .filter(function (events) {
40838             var event1 = events[0];
40839             var event2 = events[1];
40840             var event3 = events[2];
40841             return event1.type === "click" &&
40842                 event2.type === "click" &&
40843                 event3.type === "dblclick" &&
40844                 event1.target.parentNode === canvasContainer &&
40845                 event2.target.parentNode === canvasContainer;
40846         })
40847             .map(function (events) {
40848             return events[2];
40849         })
40850             .share();
40851         Observable_1.Observable
40852             .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
40853             .subscribe(function (event) {
40854             event.preventDefault();
40855         });
40856         this._mouseWheel$ = Observable_1.Observable
40857             .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"))
40858             .share();
40859         this._consistentContextMenu$ = Observable_1.Observable
40860             .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
40861             .bufferCount(3, 1)
40862             .filter(function (events) {
40863             // fire context menu on mouse up both on mac and windows
40864             return events[0].type === "mousedown" &&
40865                 events[1].type === "contextmenu" &&
40866                 events[2].type === "mouseup";
40867         })
40868             .map(function (events) {
40869             return events[1];
40870         })
40871             .share();
40872         var dragStop$ = Observable_1.Observable
40873             .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
40874             .filter(function (e) {
40875             return e.button === 0;
40876         }))
40877             .share();
40878         var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).share();
40879         this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).share();
40880         this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).share();
40881         this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).share();
40882         var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).share();
40883         this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).share();
40884         this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).share();
40885         this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).share();
40886         this._proximateClick$ = this._mouseDown$
40887             .switchMap(function (mouseDown) {
40888             return _this._click$
40889                 .takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$))
40890                 .take(1);
40891         })
40892             .share();
40893         this._staticClick$ = this._mouseDown$
40894             .switchMap(function (e) {
40895             return _this._click$
40896                 .takeUntil(_this._documentMouseMove$)
40897                 .take(1);
40898         })
40899             .share();
40900         this._mouseDragStart$.subscribe();
40901         this._mouseDrag$.subscribe();
40902         this._mouseDragEnd$.subscribe();
40903         this._domMouseDragStart$.subscribe();
40904         this._domMouseDrag$.subscribe();
40905         this._domMouseDragEnd$.subscribe();
40906         this._staticClick$.subscribe();
40907         this._mouseOwner$ = this._createOwner$(this._claimMouse$)
40908             .publishReplay(1)
40909             .refCount();
40910         this._wheelOwner$ = this._createOwner$(this._claimWheel$)
40911             .publishReplay(1)
40912             .refCount();
40913         this._mouseOwner$.subscribe(function () { });
40914         this._wheelOwner$.subscribe(function () { });
40915     }
40916     Object.defineProperty(MouseService.prototype, "active$", {
40917         get: function () {
40918             return this._active$;
40919         },
40920         enumerable: true,
40921         configurable: true
40922     });
40923     Object.defineProperty(MouseService.prototype, "activate$", {
40924         get: function () {
40925             return this._activeSubject$;
40926         },
40927         enumerable: true,
40928         configurable: true
40929     });
40930     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
40931         get: function () {
40932             return this._documentMouseMove$;
40933         },
40934         enumerable: true,
40935         configurable: true
40936     });
40937     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
40938         get: function () {
40939             return this._documentMouseUp$;
40940         },
40941         enumerable: true,
40942         configurable: true
40943     });
40944     Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
40945         get: function () {
40946             return this._domMouseDragStart$;
40947         },
40948         enumerable: true,
40949         configurable: true
40950     });
40951     Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
40952         get: function () {
40953             return this._domMouseDrag$;
40954         },
40955         enumerable: true,
40956         configurable: true
40957     });
40958     Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
40959         get: function () {
40960             return this._domMouseDragEnd$;
40961         },
40962         enumerable: true,
40963         configurable: true
40964     });
40965     Object.defineProperty(MouseService.prototype, "domMouseDown$", {
40966         get: function () {
40967             return this._domMouseDown$;
40968         },
40969         enumerable: true,
40970         configurable: true
40971     });
40972     Object.defineProperty(MouseService.prototype, "domMouseMove$", {
40973         get: function () {
40974             return this._domMouseMove$;
40975         },
40976         enumerable: true,
40977         configurable: true
40978     });
40979     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
40980         get: function () {
40981             return this._mouseOwner$;
40982         },
40983         enumerable: true,
40984         configurable: true
40985     });
40986     Object.defineProperty(MouseService.prototype, "mouseDown$", {
40987         get: function () {
40988             return this._mouseDown$;
40989         },
40990         enumerable: true,
40991         configurable: true
40992     });
40993     Object.defineProperty(MouseService.prototype, "mouseMove$", {
40994         get: function () {
40995             return this._mouseMove$;
40996         },
40997         enumerable: true,
40998         configurable: true
40999     });
41000     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
41001         get: function () {
41002             return this._mouseLeave$;
41003         },
41004         enumerable: true,
41005         configurable: true
41006     });
41007     Object.defineProperty(MouseService.prototype, "mouseOut$", {
41008         get: function () {
41009             return this._mouseOut$;
41010         },
41011         enumerable: true,
41012         configurable: true
41013     });
41014     Object.defineProperty(MouseService.prototype, "mouseOver$", {
41015         get: function () {
41016             return this._mouseOver$;
41017         },
41018         enumerable: true,
41019         configurable: true
41020     });
41021     Object.defineProperty(MouseService.prototype, "mouseUp$", {
41022         get: function () {
41023             return this._mouseUp$;
41024         },
41025         enumerable: true,
41026         configurable: true
41027     });
41028     Object.defineProperty(MouseService.prototype, "click$", {
41029         get: function () {
41030             return this._click$;
41031         },
41032         enumerable: true,
41033         configurable: true
41034     });
41035     Object.defineProperty(MouseService.prototype, "dblClick$", {
41036         get: function () {
41037             return this._dblClick$;
41038         },
41039         enumerable: true,
41040         configurable: true
41041     });
41042     Object.defineProperty(MouseService.prototype, "contextMenu$", {
41043         get: function () {
41044             return this._consistentContextMenu$;
41045         },
41046         enumerable: true,
41047         configurable: true
41048     });
41049     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
41050         get: function () {
41051             return this._mouseWheel$;
41052         },
41053         enumerable: true,
41054         configurable: true
41055     });
41056     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
41057         get: function () {
41058             return this._mouseDragStart$;
41059         },
41060         enumerable: true,
41061         configurable: true
41062     });
41063     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
41064         get: function () {
41065             return this._mouseDrag$;
41066         },
41067         enumerable: true,
41068         configurable: true
41069     });
41070     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
41071         get: function () {
41072             return this._mouseDragEnd$;
41073         },
41074         enumerable: true,
41075         configurable: true
41076     });
41077     Object.defineProperty(MouseService.prototype, "proximateClick$", {
41078         get: function () {
41079             return this._proximateClick$;
41080         },
41081         enumerable: true,
41082         configurable: true
41083     });
41084     Object.defineProperty(MouseService.prototype, "staticClick$", {
41085         get: function () {
41086             return this._staticClick$;
41087         },
41088         enumerable: true,
41089         configurable: true
41090     });
41091     MouseService.prototype.claimMouse = function (name, zindex) {
41092         this._claimMouse$.next({ name: name, zindex: zindex });
41093     };
41094     MouseService.prototype.unclaimMouse = function (name) {
41095         this._claimMouse$.next({ name: name, zindex: null });
41096     };
41097     MouseService.prototype.deferPixels = function (name, deferPixels) {
41098         this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
41099     };
41100     MouseService.prototype.undeferPixels = function (name) {
41101         this._deferPixelClaims$.next({ name: name, deferPixels: null });
41102     };
41103     MouseService.prototype.claimWheel = function (name, zindex) {
41104         this._claimWheel$.next({ name: name, zindex: zindex });
41105     };
41106     MouseService.prototype.unclaimWheel = function (name) {
41107         this._claimWheel$.next({ name: name, zindex: null });
41108     };
41109     MouseService.prototype.filtered$ = function (name, observable$) {
41110         return this._filtered(name, observable$, this._mouseOwner$);
41111     };
41112     MouseService.prototype.filteredWheel$ = function (name, observable$) {
41113         return this._filtered(name, observable$, this._wheelOwner$);
41114     };
41115     MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
41116         return mouseMove$
41117             .map(function (mouseMove) {
41118             var deltaX = mouseMove.clientX - origin.clientX;
41119             var deltaY = mouseMove.clientY - origin.clientY;
41120             return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
41121         })
41122             .withLatestFrom(this._deferPixels$)
41123             .filter(function (_a) {
41124             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
41125             return delta > deferPixels;
41126         })
41127             .map(function (_a) {
41128             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
41129             return mouseMove;
41130         });
41131     };
41132     MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
41133         var _this = this;
41134         return mouseDragStartInitiate$
41135             .map(function (_a) {
41136             var mouseDown = _a[0], mouseMove = _a[1];
41137             return mouseMove;
41138         })
41139             .switchMap(function (mouseMove) {
41140             return Observable_1.Observable
41141                 .of(mouseMove)
41142                 .concat(_this._documentMouseMove$)
41143                 .takeUntil(stop$);
41144         });
41145     };
41146     MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
41147         return mouseDragStart$
41148             .switchMap(function (event) {
41149             return stop$.first();
41150         });
41151     };
41152     MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
41153         return mouseDragStartInitiate$
41154             .map(function (_a) {
41155             var mouseDown = _a[0], mouseMove = _a[1];
41156             return mouseDown;
41157         });
41158     };
41159     MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
41160         var _this = this;
41161         return mouseDown$
41162             .filter(function (mouseDown) {
41163             return mouseDown.button === 0;
41164         })
41165             .switchMap(function (mouseDown) {
41166             return Observable_1.Observable
41167                 .combineLatest(Observable_1.Observable.of(mouseDown), defer ?
41168                 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
41169                 _this._documentMouseMove$)
41170                 .takeUntil(stop$)
41171                 .take(1);
41172         });
41173     };
41174     MouseService.prototype._createOwner$ = function (claim$) {
41175         return claim$
41176             .scan(function (claims, claim) {
41177             if (claim.zindex == null) {
41178                 delete claims[claim.name];
41179             }
41180             else {
41181                 claims[claim.name] = claim.zindex;
41182             }
41183             return claims;
41184         }, {})
41185             .map(function (claims) {
41186             var owner = null;
41187             var zIndexMax = -1;
41188             for (var name_1 in claims) {
41189                 if (!claims.hasOwnProperty(name_1)) {
41190                     continue;
41191                 }
41192                 if (claims[name_1] > zIndexMax) {
41193                     zIndexMax = claims[name_1];
41194                     owner = name_1;
41195                 }
41196             }
41197             return owner;
41198         })
41199             .startWith(null);
41200     };
41201     MouseService.prototype._filtered = function (name, observable$, owner$) {
41202         return observable$
41203             .withLatestFrom(owner$)
41204             .filter(function (_a) {
41205             var item = _a[0], owner = _a[1];
41206             return owner === name;
41207         })
41208             .map(function (_a) {
41209             var item = _a[0], owner = _a[1];
41210             return item;
41211         });
41212     };
41213     return MouseService;
41214 }());
41215 exports.MouseService = MouseService;
41216 exports.default = MouseService;
41217
41218 },{"../Geo":233,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/fromEvent":42,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/switchMap":80,"rxjs/add/operator/withLatestFrom":85}],372:[function(require,module,exports){
41219 "use strict";
41220 /// <reference path="../../typings/index.d.ts" />
41221 Object.defineProperty(exports, "__esModule", { value: true });
41222 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
41223 var Observable_1 = require("rxjs/Observable");
41224 var ReplaySubject_1 = require("rxjs/ReplaySubject");
41225 require("rxjs/add/observable/throw");
41226 require("rxjs/add/operator/do");
41227 require("rxjs/add/operator/finally");
41228 require("rxjs/add/operator/first");
41229 require("rxjs/add/operator/map");
41230 require("rxjs/add/operator/mergeMap");
41231 var API_1 = require("../API");
41232 var Graph_1 = require("../Graph");
41233 var Edge_1 = require("../Edge");
41234 var State_1 = require("../State");
41235 var Viewer_1 = require("../Viewer");
41236 var Navigator = (function () {
41237     function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
41238         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
41239         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
41240         this._graphService = graphService != null ?
41241             graphService :
41242             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
41243         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
41244         this._loadingName = "navigator";
41245         this._stateService = stateService != null ? stateService : new State_1.StateService();
41246         this._cacheService = cacheService != null ?
41247             cacheService :
41248             new Viewer_1.CacheService(this._graphService, this._stateService);
41249         this._cacheService.start();
41250         this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
41251         this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
41252         this._request$ = null;
41253         this._requestSubscription = null;
41254         this._nodeRequestSubscription = null;
41255     }
41256     Object.defineProperty(Navigator.prototype, "apiV3", {
41257         get: function () {
41258             return this._apiV3;
41259         },
41260         enumerable: true,
41261         configurable: true
41262     });
41263     Object.defineProperty(Navigator.prototype, "graphService", {
41264         get: function () {
41265             return this._graphService;
41266         },
41267         enumerable: true,
41268         configurable: true
41269     });
41270     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
41271         get: function () {
41272             return this._imageLoadingService;
41273         },
41274         enumerable: true,
41275         configurable: true
41276     });
41277     Object.defineProperty(Navigator.prototype, "loadingService", {
41278         get: function () {
41279             return this._loadingService;
41280         },
41281         enumerable: true,
41282         configurable: true
41283     });
41284     Object.defineProperty(Navigator.prototype, "movedToKey$", {
41285         get: function () {
41286             return this._movedToKey$;
41287         },
41288         enumerable: true,
41289         configurable: true
41290     });
41291     Object.defineProperty(Navigator.prototype, "stateService", {
41292         get: function () {
41293             return this._stateService;
41294         },
41295         enumerable: true,
41296         configurable: true
41297     });
41298     Navigator.prototype.moveToKey$ = function (key) {
41299         this._abortRequest("to key " + key);
41300         this._loadingService.startLoading(this._loadingName);
41301         var node$ = this._moveToKey$(key);
41302         return this._makeRequest$(node$);
41303     };
41304     Navigator.prototype.moveDir$ = function (direction) {
41305         var _this = this;
41306         this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
41307         this._loadingService.startLoading(this._loadingName);
41308         var node$ = this.stateService.currentNode$
41309             .first()
41310             .mergeMap(function (node) {
41311             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
41312                 node.sequenceEdges$ :
41313                 node.spatialEdges$)
41314                 .first()
41315                 .map(function (status) {
41316                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
41317                     var edge = _a[_i];
41318                     if (edge.data.direction === direction) {
41319                         return edge.to;
41320                     }
41321                 }
41322                 return null;
41323             });
41324         })
41325             .mergeMap(function (directionKey) {
41326             if (directionKey == null) {
41327                 _this._loadingService.stopLoading(_this._loadingName);
41328                 return Observable_1.Observable
41329                     .throw(new Error("Direction (" + direction + ") does not exist for current node."));
41330             }
41331             return _this._moveToKey$(directionKey);
41332         });
41333         return this._makeRequest$(node$);
41334     };
41335     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
41336         var _this = this;
41337         this._abortRequest("to lat " + lat + ", lon " + lon);
41338         this._loadingService.startLoading(this._loadingName);
41339         var node$ = this.apiV3.imageCloseTo$(lat, lon)
41340             .mergeMap(function (fullNode) {
41341             if (fullNode == null) {
41342                 _this._loadingService.stopLoading(_this._loadingName);
41343                 return Observable_1.Observable
41344                     .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
41345             }
41346             return _this._moveToKey$(fullNode.key);
41347         });
41348         return this._makeRequest$(node$);
41349     };
41350     Navigator.prototype.setFilter$ = function (filter) {
41351         var _this = this;
41352         this._stateService.clearNodes();
41353         return this._movedToKey$
41354             .first()
41355             .mergeMap(function (key) {
41356             if (key != null) {
41357                 return _this._trajectoryKeys$()
41358                     .mergeMap(function (keys) {
41359                     return _this._graphService.setFilter$(filter)
41360                         .mergeMap(function (graph) {
41361                         return _this._cacheKeys$(keys);
41362                     });
41363                 })
41364                     .last();
41365             }
41366             return _this._keyRequested$
41367                 .first()
41368                 .mergeMap(function (requestedKey) {
41369                 if (requestedKey != null) {
41370                     return _this._graphService.setFilter$(filter)
41371                         .mergeMap(function (graph) {
41372                         return _this._graphService.cacheNode$(requestedKey);
41373                     });
41374                 }
41375                 return _this._graphService.setFilter$(filter)
41376                     .map(function (graph) {
41377                     return undefined;
41378                 });
41379             });
41380         })
41381             .map(function (node) {
41382             return undefined;
41383         });
41384     };
41385     Navigator.prototype.setToken$ = function (token) {
41386         var _this = this;
41387         this._abortRequest("to set token");
41388         this._stateService.clearNodes();
41389         return this._movedToKey$
41390             .first()
41391             .do(function (key) {
41392             _this._apiV3.setToken(token);
41393         })
41394             .mergeMap(function (key) {
41395             return key == null ?
41396                 _this._graphService.reset$([])
41397                     .map(function (graph) {
41398                     return undefined;
41399                 }) :
41400                 _this._trajectoryKeys$()
41401                     .mergeMap(function (keys) {
41402                     return _this._graphService.reset$(keys)
41403                         .mergeMap(function (graph) {
41404                         return _this._cacheKeys$(keys);
41405                     });
41406                 })
41407                     .last()
41408                     .map(function (node) {
41409                     return undefined;
41410                 });
41411         });
41412     };
41413     Navigator.prototype._cacheKeys$ = function (keys) {
41414         var _this = this;
41415         var cacheNodes$ = keys
41416             .map(function (key) {
41417             return _this._graphService.cacheNode$(key);
41418         });
41419         return Observable_1.Observable
41420             .from(cacheNodes$)
41421             .mergeAll();
41422     };
41423     Navigator.prototype._abortRequest = function (reason) {
41424         if (this._requestSubscription != null) {
41425             this._requestSubscription.unsubscribe();
41426             this._requestSubscription = null;
41427         }
41428         if (this._nodeRequestSubscription != null) {
41429             this._nodeRequestSubscription.unsubscribe();
41430             this._nodeRequestSubscription = null;
41431         }
41432         if (this._request$ != null) {
41433             this._request$.error(new Error("Request aborted by a subsequent request " + reason + "."));
41434             this._request$ = null;
41435         }
41436     };
41437     Navigator.prototype._makeRequest$ = function (node$) {
41438         var _this = this;
41439         this._request$ = new ReplaySubject_1.ReplaySubject(1);
41440         this._requestSubscription = this._request$
41441             .subscribe(undefined, function (e) { });
41442         this._nodeRequestSubscription = node$
41443             .subscribe(function (node) {
41444             _this._request$.next(node);
41445             _this._request$.complete();
41446         }, function (error) {
41447             _this._request$.error(error);
41448         });
41449         return this._request$;
41450     };
41451     Navigator.prototype._moveToKey$ = function (key) {
41452         var _this = this;
41453         this._keyRequested$.next(key);
41454         return this._graphService.cacheNode$(key)
41455             .do(function (node) {
41456             _this._stateService.setNodes([node]);
41457             _this._movedToKey$.next(node.key);
41458         })
41459             .finally(function () {
41460             _this._loadingService.stopLoading(_this._loadingName);
41461         });
41462     };
41463     Navigator.prototype._trajectoryKeys$ = function () {
41464         return this._stateService.currentState$
41465             .first()
41466             .map(function (frame) {
41467             return frame.state.trajectory
41468                 .map(function (node) {
41469                 return node.key;
41470             });
41471         });
41472     };
41473     return Navigator;
41474 }());
41475 exports.Navigator = Navigator;
41476 exports.default = Navigator;
41477
41478 },{"../API":229,"../Edge":231,"../Graph":234,"../State":237,"../Viewer":241,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/ReplaySubject":32,"rxjs/add/observable/throw":46,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68}],373:[function(require,module,exports){
41479 "use strict";
41480 Object.defineProperty(exports, "__esModule", { value: true });
41481 var Observable_1 = require("rxjs/Observable");
41482 var Subject_1 = require("rxjs/Subject");
41483 require("rxjs/add/observable/combineLatest");
41484 require("rxjs/add/operator/distinctUntilChanged");
41485 require("rxjs/add/operator/map");
41486 require("rxjs/add/operator/throttleTime");
41487 var Viewer_1 = require("../Viewer");
41488 var Observer = (function () {
41489     function Observer(eventEmitter, navigator, container) {
41490         var _this = this;
41491         this._container = container;
41492         this._eventEmitter = eventEmitter;
41493         this._navigator = navigator;
41494         this._projection = new Viewer_1.Projection();
41495         this._started = false;
41496         this._navigable$ = new Subject_1.Subject();
41497         // navigable and loading should always emit, also when cover is activated.
41498         this._navigable$
41499             .subscribe(function (navigable) {
41500             _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
41501         });
41502         this._navigator.loadingService.loading$
41503             .subscribe(function (loading) {
41504             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
41505         });
41506     }
41507     Object.defineProperty(Observer.prototype, "started", {
41508         get: function () {
41509             return this._started;
41510         },
41511         enumerable: true,
41512         configurable: true
41513     });
41514     Object.defineProperty(Observer.prototype, "navigable$", {
41515         get: function () {
41516             return this._navigable$;
41517         },
41518         enumerable: true,
41519         configurable: true
41520     });
41521     Observer.prototype.projectBasic$ = function (basicPoint) {
41522         var _this = this;
41523         return Observable_1.Observable
41524             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
41525             .first()
41526             .map(function (_a) {
41527             var render = _a[0], transform = _a[1];
41528             var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
41529             return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
41530         });
41531     };
41532     Observer.prototype.startEmit = function () {
41533         var _this = this;
41534         if (this._started) {
41535             return;
41536         }
41537         this._started = true;
41538         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
41539             .subscribe(function (node) {
41540             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
41541         });
41542         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
41543             .switchMap(function (node) {
41544             return node.sequenceEdges$;
41545         })
41546             .subscribe(function (status) {
41547             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
41548         });
41549         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
41550             .switchMap(function (node) {
41551             return node.spatialEdges$;
41552         })
41553             .subscribe(function (status) {
41554             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
41555         });
41556         this._moveSubscription = Observable_1.Observable
41557             .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
41558             .map(function (values) {
41559             return values[0] || values[1] || values[2];
41560         })
41561             .distinctUntilChanged()
41562             .subscribe(function (started) {
41563             if (started) {
41564                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
41565             }
41566             else {
41567                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
41568             }
41569         });
41570         this._bearingSubscription = this._container.renderService.bearing$
41571             .throttleTime(100)
41572             .distinctUntilChanged(function (b1, b2) {
41573             return Math.abs(b2 - b1) < 1;
41574         })
41575             .subscribe(function (bearing) {
41576             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
41577         });
41578         var mouseMove$ = this._container.mouseService.active$
41579             .switchMap(function (active) {
41580             return active ?
41581                 Observable_1.Observable.empty() :
41582                 _this._container.mouseService.mouseMove$;
41583         });
41584         this._viewerMouseEventSubscription = Observable_1.Observable
41585             .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$))
41586             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
41587             .map(function (_a) {
41588             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
41589             var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
41590             return {
41591                 basicPoint: unprojection.basicPoint,
41592                 latLon: unprojection.latLon,
41593                 originalEvent: event,
41594                 pixelPoint: unprojection.pixelPoint,
41595                 target: _this._eventEmitter,
41596                 type: type,
41597             };
41598         })
41599             .subscribe(function (event) {
41600             _this._eventEmitter.fire(event.type, event);
41601         });
41602     };
41603     Observer.prototype.stopEmit = function () {
41604         if (!this.started) {
41605             return;
41606         }
41607         this._started = false;
41608         this._bearingSubscription.unsubscribe();
41609         this._currentNodeSubscription.unsubscribe();
41610         this._moveSubscription.unsubscribe();
41611         this._sequenceEdgesSubscription.unsubscribe();
41612         this._spatialEdgesSubscription.unsubscribe();
41613         this._viewerMouseEventSubscription.unsubscribe();
41614         this._bearingSubscription = null;
41615         this._currentNodeSubscription = null;
41616         this._moveSubscription = null;
41617         this._sequenceEdgesSubscription = null;
41618         this._spatialEdgesSubscription = null;
41619         this._viewerMouseEventSubscription = null;
41620     };
41621     Observer.prototype.unproject$ = function (canvasPoint) {
41622         var _this = this;
41623         return Observable_1.Observable
41624             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
41625             .first()
41626             .map(function (_a) {
41627             var render = _a[0], reference = _a[1], transform = _a[2];
41628             var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
41629             return unprojection.latLon;
41630         });
41631     };
41632     Observer.prototype.unprojectBasic$ = function (canvasPoint) {
41633         var _this = this;
41634         return Observable_1.Observable
41635             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
41636             .first()
41637             .map(function (_a) {
41638             var render = _a[0], transform = _a[1];
41639             return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
41640         });
41641     };
41642     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
41643         return mouseEvent$.map(function (event) {
41644             return [type, event];
41645         });
41646     };
41647     return Observer;
41648 }());
41649 exports.Observer = Observer;
41650 exports.default = Observer;
41651
41652 },{"../Viewer":241,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/throttleTime":84}],374:[function(require,module,exports){
41653 "use strict";
41654 /// <reference path="../../typings/index.d.ts" />
41655 Object.defineProperty(exports, "__esModule", { value: true });
41656 var THREE = require("three");
41657 var Geo_1 = require("../Geo");
41658 var Projection = (function () {
41659     function Projection(geoCoords, viewportCoords) {
41660         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
41661         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
41662     }
41663     Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
41664         return this._viewportCoords
41665             .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
41666     };
41667     Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
41668         var basicPoint = this._viewportCoords
41669             .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
41670         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
41671             basicPoint = null;
41672         }
41673         return basicPoint;
41674     };
41675     Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
41676         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
41677         return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
41678     };
41679     Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
41680         var canvasX = canvasPoint[0];
41681         var canvasY = canvasPoint[1];
41682         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
41683         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
41684             .unproject(render.perspective);
41685         var basicPoint = transform.projectBasic(point3d.toArray());
41686         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
41687             basicPoint = null;
41688         }
41689         var direction3d = point3d.clone().sub(render.camera.position).normalize();
41690         var dist = -2 / direction3d.z;
41691         var latLon = null;
41692         if (dist > 0 && dist < 100 && !!basicPoint) {
41693             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
41694             var latLonArray = this._geoCoords
41695                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
41696                 .slice(0, 2);
41697             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
41698         }
41699         var unprojection = {
41700             basicPoint: basicPoint,
41701             latLon: latLon,
41702             pixelPoint: [canvasX, canvasY],
41703         };
41704         return unprojection;
41705     };
41706     return Projection;
41707 }());
41708 exports.Projection = Projection;
41709 exports.default = Projection;
41710
41711 },{"../Geo":233,"three":180}],375:[function(require,module,exports){
41712 "use strict";
41713 /// <reference path="../../typings/index.d.ts" />
41714 Object.defineProperty(exports, "__esModule", { value: true });
41715 var THREE = require("three");
41716 var vd = require("virtual-dom");
41717 var Subject_1 = require("rxjs/Subject");
41718 require("rxjs/add/operator/publishReplay");
41719 require("rxjs/add/operator/scan");
41720 require("rxjs/add/operator/startWith");
41721 var Viewer_1 = require("../Viewer");
41722 var SpriteAtlas = (function () {
41723     function SpriteAtlas() {
41724     }
41725     Object.defineProperty(SpriteAtlas.prototype, "json", {
41726         set: function (value) {
41727             this._json = value;
41728         },
41729         enumerable: true,
41730         configurable: true
41731     });
41732     Object.defineProperty(SpriteAtlas.prototype, "image", {
41733         set: function (value) {
41734             this._image = value;
41735             this._texture = new THREE.Texture(this._image);
41736             this._texture.minFilter = THREE.NearestFilter;
41737         },
41738         enumerable: true,
41739         configurable: true
41740     });
41741     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
41742         get: function () {
41743             return !!(this._image && this._json);
41744         },
41745         enumerable: true,
41746         configurable: true
41747     });
41748     SpriteAtlas.prototype.getGLSprite = function (name) {
41749         if (!this.loaded) {
41750             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
41751         }
41752         var definition = this._json[name];
41753         if (!definition) {
41754             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
41755             return new THREE.Object3D();
41756         }
41757         var texture = this._texture.clone();
41758         texture.needsUpdate = true;
41759         var width = this._image.width;
41760         var height = this._image.height;
41761         texture.offset.x = definition.x / width;
41762         texture.offset.y = (height - definition.y - definition.height) / height;
41763         texture.repeat.x = definition.width / width;
41764         texture.repeat.y = definition.height / height;
41765         var material = new THREE.SpriteMaterial({ map: texture });
41766         return new THREE.Sprite(material);
41767     };
41768     SpriteAtlas.prototype.getDOMSprite = function (name, float) {
41769         if (!this.loaded) {
41770             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
41771         }
41772         if (float == null) {
41773             float = Viewer_1.Alignment.Center;
41774         }
41775         var definition = this._json[name];
41776         if (!definition) {
41777             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
41778             return vd.h("div", {}, []);
41779         }
41780         var clipTop = definition.y;
41781         var clipRigth = definition.x + definition.width;
41782         var clipBottom = definition.y + definition.height;
41783         var clipLeft = definition.x;
41784         var left = -definition.x;
41785         var top = -definition.y;
41786         var height = this._image.height;
41787         var width = this._image.width;
41788         switch (float) {
41789             case Viewer_1.Alignment.Bottom:
41790             case Viewer_1.Alignment.Center:
41791             case Viewer_1.Alignment.Top:
41792                 left -= definition.width / 2;
41793                 break;
41794             case Viewer_1.Alignment.BottomLeft:
41795             case Viewer_1.Alignment.Left:
41796             case Viewer_1.Alignment.TopLeft:
41797                 left -= definition.width;
41798                 break;
41799             case Viewer_1.Alignment.BottomRight:
41800             case Viewer_1.Alignment.Right:
41801             case Viewer_1.Alignment.BottomRight:
41802             default:
41803                 break;
41804         }
41805         switch (float) {
41806             case Viewer_1.Alignment.Center:
41807             case Viewer_1.Alignment.Left:
41808             case Viewer_1.Alignment.Right:
41809                 top -= definition.height / 2;
41810                 break;
41811             case Viewer_1.Alignment.Top:
41812             case Viewer_1.Alignment.TopLeft:
41813             case Viewer_1.Alignment.TopRight:
41814                 top -= definition.height;
41815                 break;
41816             case Viewer_1.Alignment.Bottom:
41817             case Viewer_1.Alignment.BottomLeft:
41818             case Viewer_1.Alignment.BottomRight:
41819             default:
41820                 break;
41821         }
41822         var pixelRatioInverse = 1 / definition.pixelRatio;
41823         clipTop *= pixelRatioInverse;
41824         clipRigth *= pixelRatioInverse;
41825         clipBottom *= pixelRatioInverse;
41826         clipLeft *= pixelRatioInverse;
41827         left *= pixelRatioInverse;
41828         top *= pixelRatioInverse;
41829         height *= pixelRatioInverse;
41830         width *= pixelRatioInverse;
41831         var properties = {
41832             src: this._image.src,
41833             style: {
41834                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
41835                 height: height + "px",
41836                 left: left + "px",
41837                 position: "absolute",
41838                 top: top + "px",
41839                 width: width + "px",
41840             },
41841         };
41842         return vd.h("img", properties, []);
41843     };
41844     return SpriteAtlas;
41845 }());
41846 var SpriteService = (function () {
41847     function SpriteService(sprite) {
41848         var _this = this;
41849         this._retina = window.devicePixelRatio > 1;
41850         this._spriteAtlasOperation$ = new Subject_1.Subject();
41851         this._spriteAtlas$ = this._spriteAtlasOperation$
41852             .startWith(function (atlas) {
41853             return atlas;
41854         })
41855             .scan(function (atlas, operation) {
41856             return operation(atlas);
41857         }, new SpriteAtlas())
41858             .publishReplay(1)
41859             .refCount();
41860         this._spriteAtlas$.subscribe(function () { });
41861         if (sprite == null) {
41862             return;
41863         }
41864         var format = this._retina ? "@2x" : "";
41865         var imageXmlHTTP = new XMLHttpRequest();
41866         imageXmlHTTP.open("GET", sprite + format + ".png", true);
41867         imageXmlHTTP.responseType = "arraybuffer";
41868         imageXmlHTTP.onload = function () {
41869             var image = new Image();
41870             image.onload = function () {
41871                 _this._spriteAtlasOperation$.next(function (atlas) {
41872                     atlas.image = image;
41873                     return atlas;
41874                 });
41875             };
41876             var blob = new Blob([imageXmlHTTP.response]);
41877             image.src = window.URL.createObjectURL(blob);
41878         };
41879         imageXmlHTTP.onerror = function (error) {
41880             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
41881         };
41882         imageXmlHTTP.send();
41883         var jsonXmlHTTP = new XMLHttpRequest();
41884         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
41885         jsonXmlHTTP.responseType = "text";
41886         jsonXmlHTTP.onload = function () {
41887             var json = JSON.parse(jsonXmlHTTP.response);
41888             _this._spriteAtlasOperation$.next(function (atlas) {
41889                 atlas.json = json;
41890                 return atlas;
41891             });
41892         };
41893         jsonXmlHTTP.onerror = function (error) {
41894             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
41895         };
41896         jsonXmlHTTP.send();
41897     }
41898     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
41899         get: function () {
41900             return this._spriteAtlas$;
41901         },
41902         enumerable: true,
41903         configurable: true
41904     });
41905     return SpriteService;
41906 }());
41907 exports.SpriteService = SpriteService;
41908 exports.default = SpriteService;
41909
41910 },{"../Viewer":241,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":74,"rxjs/add/operator/startWith":79,"three":180,"virtual-dom":186}],376:[function(require,module,exports){
41911 "use strict";
41912 Object.defineProperty(exports, "__esModule", { value: true });
41913 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
41914 var Observable_1 = require("rxjs/Observable");
41915 var Subject_1 = require("rxjs/Subject");
41916 require("rxjs/add/observable/timer");
41917 require("rxjs/add/operator/bufferWhen");
41918 require("rxjs/add/operator/filter");
41919 require("rxjs/add/operator/map");
41920 require("rxjs/add/operator/merge");
41921 require("rxjs/add/operator/scan");
41922 require("rxjs/add/operator/switchMap");
41923 var TouchService = (function () {
41924     function TouchService(canvasContainer, domContainer) {
41925         var _this = this;
41926         this._canvasContainer = canvasContainer;
41927         this._domContainer = domContainer;
41928         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
41929         this._active$ = this._activeSubject$
41930             .distinctUntilChanged()
41931             .publishReplay(1)
41932             .refCount();
41933         Observable_1.Observable.fromEvent(domContainer, "touchmove")
41934             .subscribe(function (event) {
41935             event.preventDefault();
41936         });
41937         this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
41938         this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
41939         this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
41940         this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
41941         var tapStart$ = this._touchStart$
41942             .filter(function (te) {
41943             return te.touches.length === 1 && te.targetTouches.length === 1;
41944         })
41945             .share();
41946         this._doubleTap$ = tapStart$
41947             .bufferWhen(function () {
41948             return tapStart$
41949                 .first()
41950                 .switchMap(function (event) {
41951                 return Observable_1.Observable
41952                     .timer(300)
41953                     .merge(tapStart$)
41954                     .take(1);
41955             });
41956         })
41957             .filter(function (events) {
41958             return events.length === 2;
41959         })
41960             .map(function (events) {
41961             return events[events.length - 1];
41962         })
41963             .share();
41964         this._doubleTap$
41965             .subscribe(function (event) {
41966             event.preventDefault();
41967         });
41968         this._singleTouchMove$ = this._touchMove$
41969             .filter(function (te) {
41970             return te.touches.length === 1 && te.targetTouches.length === 1;
41971         })
41972             .share();
41973         var singleTouchStart$ = Observable_1.Observable
41974             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
41975             .filter(function (te) {
41976             return te.touches.length === 1 && te.targetTouches.length === 1;
41977         });
41978         var multipleTouchStart$ = Observable_1.Observable
41979             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
41980             .filter(function (te) {
41981             return te.touches.length >= 1;
41982         });
41983         var touchStop$ = Observable_1.Observable
41984             .merge(this._touchEnd$, this._touchCancel$)
41985             .filter(function (te) {
41986             return te.touches.length === 0;
41987         });
41988         this._singleTouchDragStart$ = singleTouchStart$
41989             .mergeMap(function (e) {
41990             return _this._singleTouchMove$
41991                 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
41992                 .take(1);
41993         });
41994         this._singleTouchDragEnd$ = singleTouchStart$
41995             .mergeMap(function (e) {
41996             return Observable_1.Observable
41997                 .merge(touchStop$, multipleTouchStart$)
41998                 .first();
41999         });
42000         this._singleTouchDrag$ = singleTouchStart$
42001             .switchMap(function (te) {
42002             return _this._singleTouchMove$
42003                 .skip(1)
42004                 .takeUntil(Observable_1.Observable
42005                 .merge(multipleTouchStart$, touchStop$));
42006         });
42007         var touchesChanged$ = Observable_1.Observable
42008             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
42009         this._pinchStart$ = touchesChanged$
42010             .filter(function (te) {
42011             return te.touches.length === 2 && te.targetTouches.length === 2;
42012         });
42013         this._pinchEnd$ = touchesChanged$
42014             .filter(function (te) {
42015             return te.touches.length !== 2 || te.targetTouches.length !== 2;
42016         });
42017         this._pinchOperation$ = new Subject_1.Subject();
42018         this._pinch$ = this._pinchOperation$
42019             .scan(function (pinch, operation) {
42020             return operation(pinch);
42021         }, {
42022             changeX: 0,
42023             changeY: 0,
42024             clientX: 0,
42025             clientY: 0,
42026             distance: 0,
42027             distanceChange: 0,
42028             distanceX: 0,
42029             distanceY: 0,
42030             originalEvent: null,
42031             pageX: 0,
42032             pageY: 0,
42033             screenX: 0,
42034             screenY: 0,
42035             touch1: null,
42036             touch2: null,
42037         });
42038         this._touchMove$
42039             .filter(function (te) {
42040             return te.touches.length === 2 && te.targetTouches.length === 2;
42041         })
42042             .map(function (te) {
42043             return function (previous) {
42044                 var touch1 = te.touches[0];
42045                 var touch2 = te.touches[1];
42046                 var minX = Math.min(touch1.clientX, touch2.clientX);
42047                 var maxX = Math.max(touch1.clientX, touch2.clientX);
42048                 var minY = Math.min(touch1.clientY, touch2.clientY);
42049                 var maxY = Math.max(touch1.clientY, touch2.clientY);
42050                 var centerClientX = minX + (maxX - minX) / 2;
42051                 var centerClientY = minY + (maxY - minY) / 2;
42052                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
42053                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
42054                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
42055                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
42056                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
42057                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
42058                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
42059                 var distanceChange = distance - previous.distance;
42060                 var changeX = distanceX - previous.distanceX;
42061                 var changeY = distanceY - previous.distanceY;
42062                 var current = {
42063                     changeX: changeX,
42064                     changeY: changeY,
42065                     clientX: centerClientX,
42066                     clientY: centerClientY,
42067                     distance: distance,
42068                     distanceChange: distanceChange,
42069                     distanceX: distanceX,
42070                     distanceY: distanceY,
42071                     originalEvent: te,
42072                     pageX: centerPageX,
42073                     pageY: centerPageY,
42074                     screenX: centerScreenX,
42075                     screenY: centerScreenY,
42076                     touch1: touch1,
42077                     touch2: touch2,
42078                 };
42079                 return current;
42080             };
42081         })
42082             .subscribe(this._pinchOperation$);
42083         this._pinchChange$ = this._pinchStart$
42084             .switchMap(function (te) {
42085             return _this._pinch$
42086                 .skip(1)
42087                 .takeUntil(_this._pinchEnd$);
42088         });
42089     }
42090     Object.defineProperty(TouchService.prototype, "active$", {
42091         get: function () {
42092             return this._active$;
42093         },
42094         enumerable: true,
42095         configurable: true
42096     });
42097     Object.defineProperty(TouchService.prototype, "activate$", {
42098         get: function () {
42099             return this._activeSubject$;
42100         },
42101         enumerable: true,
42102         configurable: true
42103     });
42104     Object.defineProperty(TouchService.prototype, "doubleTap$", {
42105         get: function () {
42106             return this._doubleTap$;
42107         },
42108         enumerable: true,
42109         configurable: true
42110     });
42111     Object.defineProperty(TouchService.prototype, "touchStart$", {
42112         get: function () {
42113             return this._touchStart$;
42114         },
42115         enumerable: true,
42116         configurable: true
42117     });
42118     Object.defineProperty(TouchService.prototype, "touchMove$", {
42119         get: function () {
42120             return this._touchMove$;
42121         },
42122         enumerable: true,
42123         configurable: true
42124     });
42125     Object.defineProperty(TouchService.prototype, "touchEnd$", {
42126         get: function () {
42127             return this._touchEnd$;
42128         },
42129         enumerable: true,
42130         configurable: true
42131     });
42132     Object.defineProperty(TouchService.prototype, "touchCancel$", {
42133         get: function () {
42134             return this._touchCancel$;
42135         },
42136         enumerable: true,
42137         configurable: true
42138     });
42139     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
42140         get: function () {
42141             return this._singleTouchDragStart$;
42142         },
42143         enumerable: true,
42144         configurable: true
42145     });
42146     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
42147         get: function () {
42148             return this._singleTouchDrag$;
42149         },
42150         enumerable: true,
42151         configurable: true
42152     });
42153     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
42154         get: function () {
42155             return this._singleTouchDragEnd$;
42156         },
42157         enumerable: true,
42158         configurable: true
42159     });
42160     Object.defineProperty(TouchService.prototype, "pinch$", {
42161         get: function () {
42162             return this._pinchChange$;
42163         },
42164         enumerable: true,
42165         configurable: true
42166     });
42167     Object.defineProperty(TouchService.prototype, "pinchStart$", {
42168         get: function () {
42169             return this._pinchStart$;
42170         },
42171         enumerable: true,
42172         configurable: true
42173     });
42174     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
42175         get: function () {
42176             return this._pinchEnd$;
42177         },
42178         enumerable: true,
42179         configurable: true
42180     });
42181     return TouchService;
42182 }());
42183 exports.TouchService = TouchService;
42184
42185 },{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/timer":47,"rxjs/add/operator/bufferWhen":51,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/scan":74,"rxjs/add/operator/switchMap":80}],377:[function(require,module,exports){
42186 "use strict";
42187 /// <reference path="../../typings/index.d.ts" />
42188 var __extends = (this && this.__extends) || (function () {
42189     var extendStatics = Object.setPrototypeOf ||
42190         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42191         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42192     return function (d, b) {
42193         extendStatics(d, b);
42194         function __() { this.constructor = d; }
42195         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42196     };
42197 })();
42198 Object.defineProperty(exports, "__esModule", { value: true });
42199 var when = require("when");
42200 var Observable_1 = require("rxjs/Observable");
42201 var Viewer_1 = require("../Viewer");
42202 var Utils_1 = require("../Utils");
42203 /**
42204  * @class Viewer
42205  *
42206  * @classdesc The Viewer object represents the navigable photo viewer.
42207  * Create a Viewer by specifying a container, client ID, photo key and
42208  * other options. The viewer exposes methods and events for programmatic
42209  * interaction.
42210  *
42211  * The viewer works with a few different coordinate systems.
42212  *
42213  * Container pixel coordinates
42214  *
42215  * Pixel coordinates are coordinates on the viewer container. The origin is
42216  * in the top left corner of the container. The axes are
42217  * directed according to the following for a viewer container with a width
42218  * of 640 pixels and height of 480 pixels.
42219  *
42220  * ```
42221  * (0,0)                          (640, 0)
42222  *      +------------------------>
42223  *      |
42224  *      |
42225  *      |
42226  *      v                        +
42227  * (0, 480)                       (640, 480)
42228  * ```
42229  *
42230  * Basic image coordinates
42231  *
42232  * Basic image coordinates represents points in the original image adjusted for
42233  * orientation. They range from 0 to 1 on both axes. The origin is in the top left
42234  * corner of the image and the axes are directed
42235  * according to the following for all image types.
42236  *
42237  * ```
42238  * (0,0)                          (1, 0)
42239  *      +------------------------>
42240  *      |
42241  *      |
42242  *      |
42243  *      v                        +
42244  * (0, 1)                         (1, 1)
42245  * ```
42246  *
42247  * For every camera viewing direction it is possible to convert between these
42248  * two coordinate systems for the current node. The image can be panned and
42249  * zoomed independently of the size of the viewer container resulting in
42250  * different conversion results for different viewing directions.
42251  */
42252 var Viewer = (function (_super) {
42253     __extends(Viewer, _super);
42254     /**
42255      * Create a new viewer instance.
42256      *
42257      * @param {string} id - Required `id` of a DOM element which will
42258      * be transformed into the viewer.
42259      * @param {string} clientId - Required `Mapillary API ClientID`. Can
42260      * be obtained from https://www.mapillary.com/app/settings/developers.
42261      * @param {string} [key] - Optional `photoId` to start from, can be any
42262      * Mapillary photo, if null no image is loaded.
42263      * @param {IViewerOptions} [options] - Optional configuration object
42264      * specifing Viewer's initial setup.
42265      * @param {string} [token] - Optional bearer token for API requests of
42266      * protected resources.
42267      *
42268      * @example
42269      * ```
42270      * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<my key>");
42271      * ```
42272      */
42273     function Viewer(id, clientId, key, options, token) {
42274         var _this = _super.call(this) || this;
42275         options = options != null ? options : {};
42276         Utils_1.Settings.setOptions(options);
42277         _this._navigator = new Viewer_1.Navigator(clientId, token);
42278         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
42279         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
42280         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
42281         return _this;
42282     }
42283     Object.defineProperty(Viewer.prototype, "isNavigable", {
42284         /**
42285          * Return a boolean indicating if the viewer is in a navigable state.
42286          *
42287          * @description The navigable state indicates if the viewer supports
42288          * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
42289          * methods. The viewer will not be in a navigable state if the cover
42290          * is activated and the viewer has been supplied a key. When the cover
42291          * is deactivated or activated without being supplied a key it will
42292          * be navigable.
42293          *
42294          * @returns {boolean} Boolean indicating whether the viewer is navigable.
42295          */
42296         get: function () {
42297             return this._componentController.navigable;
42298         },
42299         enumerable: true,
42300         configurable: true
42301     });
42302     /**
42303      * Activate a component.
42304      *
42305      * @param {string} name - Name of the component which will become active.
42306      *
42307      * @example
42308      * ```
42309      * viewer.activateComponent("marker");
42310      * ```
42311      */
42312     Viewer.prototype.activateComponent = function (name) {
42313         this._componentController.activate(name);
42314     };
42315     /**
42316      * Activate the cover (deactivates all other components).
42317      */
42318     Viewer.prototype.activateCover = function () {
42319         this._componentController.activateCover();
42320     };
42321     /**
42322      * Deactivate a component.
42323      *
42324      * @param {string} name - Name of component which become inactive.
42325      *
42326      * @example
42327      * ```
42328      * viewer.deactivateComponent("mouse");
42329      * ```
42330      */
42331     Viewer.prototype.deactivateComponent = function (name) {
42332         this._componentController.deactivate(name);
42333     };
42334     /**
42335      * Deactivate the cover (activates all components marked as active).
42336      */
42337     Viewer.prototype.deactivateCover = function () {
42338         this._componentController.deactivateCover();
42339     };
42340     /**
42341      * Get the bearing of the current viewer camera.
42342      *
42343      * @description The bearing depends on how the camera
42344      * is currently rotated and does not correspond
42345      * to the compass angle of the current node if the view
42346      * has been panned.
42347      *
42348      * Bearing is measured in degrees clockwise with respect to
42349      * north.
42350      *
42351      * @returns {Promise<number>} Promise to the bearing
42352      * of the current viewer camera.
42353      *
42354      * @example
42355      * ```
42356      * viewer.getBearing().then((b) => { console.log(b); });
42357      * ```
42358      */
42359     Viewer.prototype.getBearing = function () {
42360         var _this = this;
42361         return when.promise(function (resolve, reject) {
42362             _this._container.renderService.bearing$
42363                 .first()
42364                 .subscribe(function (bearing) {
42365                 resolve(bearing);
42366             }, function (error) {
42367                 reject(error);
42368             });
42369         });
42370     };
42371     /**
42372      * Get the basic coordinates of the current photo that is
42373      * at the center of the viewport.
42374      *
42375      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
42376      * and have the origin point, (0, 0), at the top left corner and the
42377      * maximum value, (1, 1), at the bottom right corner of the original
42378      * photo.
42379      *
42380      * @returns {Promise<number[]>} Promise to the basic coordinates
42381      * of the current photo at the center for the viewport.
42382      *
42383      * @example
42384      * ```
42385      * viewer.getCenter().then((c) => { console.log(c); });
42386      * ```
42387      */
42388     Viewer.prototype.getCenter = function () {
42389         var _this = this;
42390         return when.promise(function (resolve, reject) {
42391             _this._navigator.stateService.getCenter()
42392                 .subscribe(function (center) {
42393                 resolve(center);
42394             }, function (error) {
42395                 reject(error);
42396             });
42397         });
42398     };
42399     /**
42400      * Get a component.
42401      *
42402      * @param {string} name - Name of component.
42403      * @returns {Component} The requested component.
42404      *
42405      * @example
42406      * ```
42407      * var mouseComponent = viewer.getComponent("mouse");
42408      * ```
42409      */
42410     Viewer.prototype.getComponent = function (name) {
42411         return this._componentController.get(name);
42412     };
42413     /**
42414      * Returns the viewer's containing HTML element.
42415      *
42416      * @returns {HTMLElement} The viewer's container.
42417      */
42418     Viewer.prototype.getContainer = function () {
42419         return this._container.element;
42420     };
42421     /**
42422      * Get the photo's current zoom level.
42423      *
42424      * @returns {Promise<number>} Promise to the viewers's current
42425      * zoom level.
42426      *
42427      * @example
42428      * ```
42429      * viewer.getZoom().then((z) => { console.log(z); });
42430      * ```
42431      */
42432     Viewer.prototype.getZoom = function () {
42433         var _this = this;
42434         return when.promise(function (resolve, reject) {
42435             _this._navigator.stateService.getZoom()
42436                 .subscribe(function (zoom) {
42437                 resolve(zoom);
42438             }, function (error) {
42439                 reject(error);
42440             });
42441         });
42442     };
42443     /**
42444      * Move close to given latitude and longitude.
42445      *
42446      * @description Because the method propagates IO errors, these potential errors
42447      * need to be handled by the method caller (see example).
42448      *
42449      * @param {Number} lat - Latitude, in degrees.
42450      * @param {Number} lon - Longitude, in degrees.
42451      * @returns {Promise<Node>} Promise to the node that was navigated to.
42452      * @throws {Error} If no nodes exist close to provided latitude
42453      * longitude.
42454      * @throws {Error} Propagates any IO errors to the caller.
42455      * @throws {Error} When viewer is not navigable.
42456      *
42457      * @example
42458      * ```
42459      * viewer.moveCloseTo(0, 0).then(
42460      *     (n) => { console.log(n); },
42461      *     (e) => { console.error(e); });
42462      * ```
42463      */
42464     Viewer.prototype.moveCloseTo = function (lat, lon) {
42465         var moveCloseTo$ = this.isNavigable ?
42466             this._navigator.moveCloseTo$(lat, lon) :
42467             Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
42468         return when.promise(function (resolve, reject) {
42469             moveCloseTo$.subscribe(function (node) {
42470                 resolve(node);
42471             }, function (error) {
42472                 reject(error);
42473             });
42474         });
42475     };
42476     /**
42477      * Navigate in a given direction.
42478      *
42479      * @description This method has to be called through EdgeDirection enumeration as in the example.
42480      *
42481      * @param {EdgeDirection} dir - Direction in which which to move.
42482      * @returns {Promise<Node>} Promise to the node that was navigated to.
42483      * @throws {Error} If the current node does not have the edge direction
42484      * or the edges has not yet been cached.
42485      * @throws {Error} Propagates any IO errors to the caller.
42486      * @throws {Error} When viewer is not navigable.
42487      *
42488      * @example
42489      * ```
42490      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
42491      *     (n) => { console.log(n); },
42492      *     (e) => { console.error(e); });
42493      * ```
42494      */
42495     Viewer.prototype.moveDir = function (dir) {
42496         var moveDir$ = this.isNavigable ?
42497             this._navigator.moveDir$(dir) :
42498             Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable."));
42499         return when.promise(function (resolve, reject) {
42500             moveDir$.subscribe(function (node) {
42501                 resolve(node);
42502             }, function (error) {
42503                 reject(error);
42504             });
42505         });
42506     };
42507     /**
42508      * Navigate to a given photo key.
42509      *
42510      * @param {string} key - A valid Mapillary photo key.
42511      * @returns {Promise<Node>} Promise to the node that was navigated to.
42512      * @throws {Error} Propagates any IO errors to the caller.
42513      * @throws {Error} When viewer is not navigable.
42514      *
42515      * @example
42516      * ```
42517      * viewer.moveToKey("<my key>").then(
42518      *     (n) => { console.log(n); },
42519      *     (e) => { console.error(e); });
42520      * ```
42521      */
42522     Viewer.prototype.moveToKey = function (key) {
42523         var moveToKey$ = this.isNavigable ?
42524             this._navigator.moveToKey$(key) :
42525             Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable."));
42526         return when.promise(function (resolve, reject) {
42527             moveToKey$.subscribe(function (node) {
42528                 resolve(node);
42529             }, function (error) {
42530                 reject(error);
42531             });
42532         });
42533     };
42534     /**
42535      * Project basic image coordinates for the current node to canvas pixel
42536      * coordinates.
42537      *
42538      * @description The basic image coordinates may not always correspond to a
42539      * pixel point that lies in the visible area of the viewer container.
42540      *
42541      * @param {Array<number>} basicPoint - Basic images coordinates to project.
42542      * @returns {Promise<ILatLon>} Promise to the pixel coordinates corresponding
42543      * to the basic image point.
42544      *
42545      * @example
42546      * ```
42547      * viewer.projectFromBasic([0.3, 0.7])
42548      *     .then((pixelPoint) => { console.log(pixelPoint); });
42549      * ```
42550      */
42551     Viewer.prototype.projectFromBasic = function (basicPoint) {
42552         var _this = this;
42553         return when.promise(function (resolve, reject) {
42554             _this._observer.projectBasic$(basicPoint)
42555                 .subscribe(function (pixelPoint) {
42556                 resolve(pixelPoint);
42557             }, function (error) {
42558                 reject(error);
42559             });
42560         });
42561     };
42562     /**
42563      * Detect the viewer's new width and height and resize it.
42564      *
42565      * @description The components will also detect the viewer's
42566      * new size and resize their rendered elements if needed.
42567      *
42568      * @example
42569      * ```
42570      * viewer.resize();
42571      * ```
42572      */
42573     Viewer.prototype.resize = function () {
42574         this._container.renderService.resize$.next(null);
42575         this._componentController.resize();
42576     };
42577     /**
42578      * Set a bearer token for authenticated API requests of
42579      * protected resources.
42580      *
42581      * @description When the supplied token is null or undefined,
42582      * any previously set bearer token will be cleared and the
42583      * viewer will make unauthenticated requests.
42584      *
42585      * Calling setAuthToken aborts all outstanding move requests.
42586      * The promises of those move requests will be rejected and
42587      * the rejections need to be caught.
42588      *
42589      * @param {string} [token] token - Bearer token.
42590      * @returns {Promise<void>} Promise that resolves after token
42591      * is set.
42592      *
42593      * @throws {Error} When viewer is not navigable.
42594      *
42595      * @example
42596      * ```
42597      * viewer.setAuthToken("<my token>")
42598      *     .then(() => { console.log("token set"); });
42599      * ```
42600      */
42601     Viewer.prototype.setAuthToken = function (token) {
42602         var setToken$ = this.isNavigable ?
42603             this._navigator.setToken$(token) :
42604             Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
42605         return when.promise(function (resolve, reject) {
42606             setToken$
42607                 .subscribe(function () {
42608                 resolve(undefined);
42609             }, function (error) {
42610                 reject(error);
42611             });
42612         });
42613     };
42614     /**
42615      * Set the basic coordinates of the current photo to be in the
42616      * center of the viewport.
42617      *
42618      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
42619      * and has the origin point, (0, 0), at the top left corner and the
42620      * maximum value, (1, 1), at the bottom right corner of the original
42621      * photo.
42622      *
42623      * @param {number[]} The basic coordinates of the current
42624      * photo to be at the center for the viewport.
42625      *
42626      * @example
42627      * ```
42628      * viewer.setCenter([0.5, 0.5]);
42629      * ```
42630      */
42631     Viewer.prototype.setCenter = function (center) {
42632         this._navigator.stateService.setCenter(center);
42633     };
42634     /**
42635      * Set the filter selecting nodes to use when calculating
42636      * the spatial edges.
42637      *
42638      * @description The following filter types are supported:
42639      *
42640      * Comparison
42641      *
42642      * `["==", key, value]` equality: `node[key] = value`
42643      *
42644      * `["!=", key, value]` inequality: `node[key] ≠ value`
42645      *
42646      * `["<", key, value]` less than: `node[key] < value`
42647      *
42648      * `["<=", key, value]` less than or equal: `node[key] ≤ value`
42649      *
42650      * `[">", key, value]` greater than: `node[key] > value`
42651      *
42652      * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
42653      *
42654      * Set membership
42655      *
42656      * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
42657      *
42658      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
42659      *
42660      * Combining
42661      *
42662      * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
42663      *
42664      * A key must be a string that identifies a node property name. A value must be
42665      * a string, number, or boolean. Strictly-typed comparisons are used. The values
42666      * `f0, ..., fn` of the combining filter must be filter expressions.
42667      *
42668      * Clear the filter by setting it to null or empty array.
42669      *
42670      * @param {FilterExpression} filter - The filter expression.
42671      * @returns {Promise<void>} Promise that resolves after filter is applied.
42672      *
42673      * @example
42674      * ```
42675      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
42676      * ```
42677      */
42678     Viewer.prototype.setFilter = function (filter) {
42679         var _this = this;
42680         return when.promise(function (resolve, reject) {
42681             _this._navigator.setFilter$(filter)
42682                 .subscribe(function () {
42683                 resolve(undefined);
42684             }, function (error) {
42685                 reject(error);
42686             });
42687         });
42688     };
42689     /**
42690      * Set the viewer's render mode.
42691      *
42692      * @param {RenderMode} renderMode - Render mode.
42693      *
42694      * @example
42695      * ```
42696      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
42697      * ```
42698      */
42699     Viewer.prototype.setRenderMode = function (renderMode) {
42700         this._container.renderService.renderMode$.next(renderMode);
42701     };
42702     /**
42703      * Set the photo's current zoom level.
42704      *
42705      * @description Possible zoom level values are on the [0, 3] interval.
42706      * Zero means zooming out to fit the photo to the view whereas three
42707      * shows the highest level of detail.
42708      *
42709      * @param {number} The photo's current zoom level.
42710      *
42711      * @example
42712      * ```
42713      * viewer.setZoom(2);
42714      * ```
42715      */
42716     Viewer.prototype.setZoom = function (zoom) {
42717         this._navigator.stateService.setZoom(zoom);
42718     };
42719     /**
42720      * Unproject canvas pixel coordinates to an ILatLon representing geographical
42721      * coordinates.
42722      *
42723      * @description The pixel point may not always correspond to geographical
42724      * coordinates. In the case of no correspondence the returned value will
42725      * be `null`.
42726      *
42727      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
42728      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
42729      *
42730      * @example
42731      * ```
42732      * viewer.unproject([100, 100])
42733      *     .then((latLon) => { console.log(latLon); });
42734      * ```
42735      */
42736     Viewer.prototype.unproject = function (pixelPoint) {
42737         var _this = this;
42738         return when.promise(function (resolve, reject) {
42739             _this._observer.unproject$(pixelPoint)
42740                 .subscribe(function (latLon) {
42741                 resolve(latLon);
42742             }, function (error) {
42743                 reject(error);
42744             });
42745         });
42746     };
42747     /**
42748      * Unproject canvas pixel coordinates to basic image coordinates for the
42749      * current node.
42750      *
42751      * @description The pixel point may not always correspond to basic image
42752      * coordinates. In the case of no correspondence the returned value will
42753      * be `null`.
42754      *
42755      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
42756      * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
42757      * to the pixel point.
42758      *
42759      * @example
42760      * ```
42761      * viewer.unprojectToBasic([100, 100])
42762      *     .then((basicPoint) => { console.log(basicPoint); });
42763      * ```
42764      */
42765     Viewer.prototype.unprojectToBasic = function (pixelPoint) {
42766         var _this = this;
42767         return when.promise(function (resolve, reject) {
42768             _this._observer.unprojectBasic$(pixelPoint)
42769                 .subscribe(function (basicPoint) {
42770                 resolve(basicPoint);
42771             }, function (error) {
42772                 reject(error);
42773             });
42774         });
42775     };
42776     /**
42777      * Fired when the viewing direction of the camera changes.
42778      * @event
42779      * @type {number} bearing - Value indicating the current bearing
42780      * measured in degrees clockwise with respect to north.
42781      */
42782     Viewer.bearingchanged = "bearingchanged";
42783     /**
42784      * Fired when a pointing device (usually a mouse) is pressed and released at
42785      * the same point in the viewer.
42786      * @event
42787      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42788      */
42789     Viewer.click = "click";
42790     /**
42791      * Fired when the right button of the mouse is clicked within the viewer.
42792      * @event
42793      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42794      */
42795     Viewer.contextmenu = "contextmenu";
42796     /**
42797      * Fired when a pointing device (usually a mouse) is clicked twice at
42798      * the same point in the viewer.
42799      * @event
42800      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42801      */
42802     Viewer.dblclick = "dblclick";
42803     /**
42804      * Fired when the viewer is loading more data.
42805      * @event
42806      * @type {boolean} loading - Boolean indicating whether the viewer is loading.
42807      */
42808     Viewer.loadingchanged = "loadingchanged";
42809     /**
42810      * Fired when a pointing device (usually a mouse) is pressed within the viewer.
42811      * @event
42812      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42813      */
42814     Viewer.mousedown = "mousedown";
42815     /**
42816      * Fired when a pointing device (usually a mouse) is moved within the viewer.
42817      * @description Will not fire when the mouse is actively used, e.g. for drag pan.
42818      * @event
42819      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42820      */
42821     Viewer.mousemove = "mousemove";
42822     /**
42823      * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
42824      * @event
42825      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42826      */
42827     Viewer.mouseout = "mouseout";
42828     /**
42829      * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
42830      * @event
42831      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42832      */
42833     Viewer.mouseover = "mouseover";
42834     /**
42835      * Fired when a pointing device (usually a mouse) is released within the viewer.
42836      * @event
42837      * @type {IViewerMouseEvent} event - Viewer mouse event data.
42838      */
42839     Viewer.mouseup = "mouseup";
42840     /**
42841      * Fired when the viewer motion stops and it is in a fixed
42842      * position with a fixed point of view.
42843      * @event
42844      */
42845     Viewer.moveend = "moveend";
42846     /**
42847      * Fired when the motion from one view to another start,
42848      * either by changing the position (e.g. when changing node) or
42849      * when changing point of view (e.g. by interaction such as pan and zoom).
42850      * @event
42851      */
42852     Viewer.movestart = "movestart";
42853     /**
42854      * Fired when the navigable state of the viewer changes.
42855      *
42856      * @description The navigable state indicates if the viewer supports
42857      * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
42858      * methods. The viewer will not be in a navigable state if the cover
42859      * is activated and the viewer has been supplied a key. When the cover
42860      * is deactivated or activated without being supplied a key it will
42861      * be navigable.
42862      *
42863      * @event
42864      * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
42865      */
42866     Viewer.navigablechanged = "navigablechanged";
42867     /**
42868      * Fired every time the viewer navigates to a new node.
42869      * @event
42870      * @type {Node} node - Current node.
42871      */
42872     Viewer.nodechanged = "nodechanged";
42873     /**
42874      * Fired every time the sequence edges of the current node changes.
42875      * @event
42876      * @type {IEdgeStatus} status - The edge status object.
42877      */
42878     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
42879     /**
42880      * Fired every time the spatial edges of the current node changes.
42881      * @event
42882      * @type {IEdgeStatus} status - The edge status object.
42883      */
42884     Viewer.spatialedgeschanged = "spatialedgeschanged";
42885     return Viewer;
42886 }(Utils_1.EventEmitter));
42887 exports.Viewer = Viewer;
42888
42889 },{"../Utils":240,"../Viewer":241,"rxjs/Observable":29,"when":227}]},{},[235])(235)
42890 });
42891 //# sourceMappingURL=mapillary.js.map